The installation

  1. The most recommended way is to use Anaconda

    conda install request
  2. If you do not want to install Anaconda, you can install it using PIP

    pip install request
  3. Localized Httpbin test tool

    pip install gunicorn httpbin

    gunicorn httpbin:app(Not supported on Windows)

Basic usage

url = 'http://httpbin.org/'
r = requests.get(url, 'get')
r = requests.post(url, 'post')
r = requests.put(url, 'put')
r = requests.delete('http://httpbin.org/delete')
r = requests.head('http://httpbin.org/get')
r = requests.options('http://httpbin.org/get')
Copy the code

Get, for example, is to send a request in get mode, get a Response class result R, and then obtain the required HTTP related information from R. request.get(‘http://httpbin.org/’, ‘get’) == request.get(‘http://httpbin.org/get’)

Passing URL parameters

Movie.douban.com/subject/304… A similar link format is: < protocol >://< domain name >/< interface >? < key 1>=< value 1>&< key 2>=< value 2> The Resquest library allows params keyword arguments to be supplied in a string dictionary.

param = {'key1': 'value1'.'key2': 'value2'}
r = requests.get("http://httpbin.org/get", params=param)
print(r.url)
>>http://httpbin.org/get?key2=value2&key1=value1
Copy the code

By printing out the URL, you can see that the URL is encoded correctly, with two caveats:

  1. The dictionary value is zeroNoneThe key is not added to the query string of the URL
  2. Dictionaries can be added to the QUERY string of urls using lists as key values
param = {'key1': 'value1'.'key2': None }
r = requests.get("http://httpbin.org/get", params=param)
print(r.url)
>>http://httpbin.org/get?key1=value1
param = {'key1': 'value1'.'key2': ['value2'.'value3']}
r = requests.get("http://httpbin.org/get", params=param)
print(r.url)
>>http://httpbin.org/get?key2=value2&key2=value3&key1=value1
Copy the code

Response content

Requests actively decodes content from the server, and most Unicode character sets can be decoded seamlessly

import requests
r = requests.get('https://api.github.com/events')
r.text
#
      
        uses its inferred text encoding
      
r.encoding
# Review the encoding used for Requests
r.encoding = 'utf-8'
# Change the encoding used for Requests
r.content
#
      
        get the encoding
      
#Requests automatically decodes gZIP and Deflatte transport encoded response data
Copy the code

Requests can also use custom encodings if needed. If you create your own encodings and register them using the Codecs module, you can easily use the decoder name as the value of R.encoding and let Requests handle the encodings.

JSON response

import requests
r = requests.get('https://api.github.com/events')
r.json()
>>[{u'repository': {u'open_issues': 0, u'url': 'https://github.com/...
Copy the code

If the JSON decoding fails, r.son () will raise an exception. For example, if the response is 401(Unauthorized), attempting to access R.son () will raise ValueError: No JSON object could be decoded. A successful call to r.son () does not mean a successful response, and a failed response may also contain JSON objects (such as HTTP 500 error details). To check whether the request was successful, use r.aise_for_status () or check that r.tatus_code is the same as expected. r.status_code == requests.codes.ok

Custom response headers

If you want to add an HTTP header to a request, you can do so by simply passing a dict to the header.

url = 'https://api.github.com/some/endpoint'
headers = {'user-agent': 'my - app / 0.0.1'}
r = requests.get(url, headers=headers)
#Attention: Custom headers take precedence over certain information sources
Copy the code
  • If the.netrcIf the user authentication information is set, the authorization using headers= will not take effect. If auth= is set,.netrcIs invalid
  • If redirected to another host, the authorization header is deleted
  • The proxy authorization header is overwritten by the proxy identity provided in the URL
  • Header content-Length is overwritten in cases where we can determine the Length of the Content

Redirection and request history

By default, Request handles all redirects automatically except HEAD, and you can use the history method of the response object to track redirects. Response.history is a list of Response objects that were created to complete the request, sorted from oldest to most recent.

r = requests.get('http://github.com')
    print(r.url)
    print(r.status_code)
    print(r.history)
>>https://github.com/
>>200
>>[<Response [301]>]
Copy the code

If you use GET/ OPTIONS/ POST/ PUT/ PATCH/ HEAD/ DELETE, you can disable redirect processing with the allow_redirects parameter.

Timeout response

Almost all production code should use this parameter. If not, the program may permanently lose response requests. Get (‘http://github.com’, timeout=0.001)

  • referred:
  • Github.com/kennethreit…
  • docs.python-requests.org/en/master/