Home >Backend Development >Python Tutorial >Summary and Summary 1: Use of Requests

Summary and Summary 1: Use of Requests

coldplay.xixi
coldplay.xixiforward
2020-11-19 17:17:553974browse

python video tutorial Column summarizes the use of Requests

Summary and Summary 1: Use of Requests

This article is organized based on official documents, and the data interfaces are all provided in official documents

According to the official document, requests is a non-GMO Python HTTP library . Powerful functions and concise syntax. It can be said that requests are inevitable when writing web programs in Python.
Although requests are simple to use, most of their functions do not need to be used frequently. But it is more cumbersome to check the documentation when you need to use it. So I also want to make a sorting and summary. It is convenient for yourself and others.

Attach the official document address

# 安装。注意,千万别安装成request,别少了末尾的spip install resquests复制代码

Basic request

First import the Requests module

import requests复制代码

Various request methods

r = requests.get('http://httpbin.org/get')# post带参r = requests.post('http://httpbin.org/post', data={'key': 'value'})
r = requests.put('http://httpbin.org/put', data={'key': 'value'})
r = requests.delete('http://httpbin.org/delete')
r = requests.head('http://httpbin.org/get')
r = requests.options('http://httpbin.org/get')复制代码

requests allows passing URL parameters. By passing parameter key-value pairs to the params variable, requests will automatically build the corresponding URL.

payload = {'key1': 'value1', 'key2': 'value2'}
r = requests.get("http://httpbin.org/get", params=payload)# 注意,字典里值为的None的键并不会被拼接到URL中# 同时,你还可以将列表作为值进行传入payload = {'key1': 'value1', 'key2': ['value2', 'value3']}
r = requests.get('http://httpbin.org/get', params=payload)
print(r.url)>>> http://httpbin.org/get?key1=value1&key2=value2&key2=value3复制代码

Response content

Returns the Unicode data of the response content through text. requests automatically decodes content from the server.

# 在需要读取文本信息时,可使用text进行获取r = requests.get('http://httpbin.org/get')
r.text复制代码

Returns the bytes (binary) data of the response content through content.

# 在需要获取文件时,可通过content获取# 例如获取一张图片并保存r = requests.get('http://httpbin.org/get/xxx.jpg')with open('example.jpg', 'wb') as img:
    img.write(r)复制代码

Process the response json data through json().

import requests
r = requests.get('http://httpbin.org/get')
r.json()复制代码

Customized request header

Add headers to the request, just pass dict to the headers parameter

# HTTP头部大小写是不敏感的headers = {    'token': token,    'content-type': 'application/json'}
url = 'http://httpbin.org/get'r = requests.get(url, headers=headers)复制代码

POST sends non-form data

When the post request has a request body, you can use the json module to encode the data

url = 'http://httpbin.org/get'body = {'data': data}
r = requests.post(url, data=json.dumps(body))复制代码

In addition to using jsonIn addition to encoding, you can also directly pass the value of the json parameter

url = 'http://httpbin.org/get'body = {'data': data}
r = requests.post(url, json=body)复制代码

Upload the file through POST

Use the open method to read in binary form After fetching the file, you can easily upload the file

url = 'http://httpbin.org/post'files = {'file': open('report.xls', 'rb')}
r = requests.post(url, files=files)# 同时,可以显式地设置文件名、文件类型和请求头url = 'http://httpbin.org/post'files = {'file': ('report.xls', open('report.xls', 'rb'), 'application/vnd.ms-excel', {'Expires': '0'})}
r = requests.post(url, files=files)复制代码

Send cookie

You can pass the cookie by passing parameters to the parametercookies

url = 'http://httpbin.org/cookies'cookies = dict(cookies_are='working')
r = requests.get(url, cookies=cookies)# 在跨域使用时,可以通过RequestsCookieJar进行域名和路径的定义jar = requests.cookies.RequestsCookieJar()
jar.set('tasty_cookie', 'yum', domain='httpbin.org', path='/cookies')
jar.set('gross_cookie', 'blech', domain='httpbin.org', path='/elsewhere')
url = 'http://httpbin.org/cookies'r = requests.get(url, cookies=jar)复制代码

Get response information

Get the response status code throughstatus_code

r = requests.get('http://httpbin.org/get')
r.status_code>>> 200# requests内置一个状态码查询对象print(r.status_code == requests.codes.ok)>>> True# 如果发生了4xx或者5xx的错误响应,可以使用raise_for_status()函数来抛出异常bad_r = requests.get('http://httpbin.org/status/404')
bad_r.status_code>>> 404bad_r.raise_for_status()# 如果请求没有发生错误,则raise_for_status()返回None复制代码

Get the response header throughheaders

r = requests.get('http://httpbin.org/get')
r.headers>>> {       'content-encoding': 'gzip',       'transfer-encoding': 'chunked',       'connection': 'close',       'server': 'nginx/1.0.4',       'x-runtime': '148ms',       'etag': '"e1ca502697e5c9317743dc078f67693f"',       'content-type': 'application/json'
   }   
# 同时,我们可以通过任意大小写形式来访问这些响应头字段r.headers['Content-Type']>>> 'application/json'r.headers.get('content-type')>>> 'application/json'复制代码

pass cookiesGet cookie data

url = 'http://example.com/some/cookie/setting/url'r = requests.get(url)
r.cookies['example_cookie_name']>>> 'example_cookie_value'复制代码

Redirect and request history

By default, except for HEAD requests, requests will automatically handle all redirects
You can pass historyMethod to track redirects

# 例如Github 将所有的HTTP请求重定向到HTTPSr = requests.get('http://github.com')

r.url>>> 'https://github.com/'r.status_code>>> 200# 如果使用的时GET、OPTIONS、POST、PUT、PATCH、DELETE请求时,可以通过设置allow_redirects=False来禁用重定向r = requests.get('http://github.com', allow_redirects=False)
r.status_code>>> 301# 也可以通过设置allow_redirects=True来启用HEAD请求的重定向r = requests.head('http://github.com', allow_redirects=True)复制代码

Finally

This article is a summary of the basic use of requests. Later, we will refer to the official documentation to summarize some advanced usage. Let’s sort out the advanced usage of requests. Proficient use of requests will have the effect of getting twice the result with half the effort when doing web development.

Related free learning recommendations: python video tutorial

The above is the detailed content of Summary and Summary 1: Use of Requests. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:juejin.im. If there is any infringement, please contact admin@php.cn delete