Home > Backend Development > Python Tutorial > Quick start introduction to python requests

Quick start introduction to python requests

巴扎黑
Release: 2017-09-02 13:18:19
Original
1442 people have browsed it

This article mainly introduces the quick start tutorial for using python requests. It is very simple to use Requests to send network requests. For specific operation methods, please refer to this article.

Get started quickly

Can’t wait? This page provides a great guide on how to get started with Requests. It assumes you have Requests installed. If you haven't yet, go to the installation section and take a look.

First, make sure:

Requests is installed

Requests is up to date

Let’s start with some simple examples.

Send a request

Sending a network request using Requests is very simple.

First import the Requests module:


>>> import requests
Copy after login

Then, try to get a web page. In this example, let’s get Github’s public timeline:


>>> r = requests.get('https://github.com/timeline.json')
Copy after login

Now, we have a Response object named r. We can get all the information we want from this object.

Requests Simple API means all HTTP request types are obvious. For example, you could send an HTTP POST request like this:


>>> r = requests.post(http://httpbin.org/post)
Copy after login

Pretty, right? What about the other HTTP request types: PUT, DELETE, HEAD, and OPTIONS? They are all the same simple:


>>> r = requests.put("http://httpbin.org/put")
>>> r = requests.delete("http://httpbin.org/delete")
>>> r = requests.head("http://httpbin.org/get")
>>> r = requests.options(http://httpbin.org/get)
Copy after login

They are all good, but this is only the tip of the iceberg of Requests.

Passing URL Parameters

You may often want to pass some kind of data for the URL's query string. If you build the URL by hand, the data is placed in the URL as key/value pairs, followed by a question mark. For example, httpbin.org/get?key=val. Requests allow you to use the params keyword argument to provide these parameters as a dictionary of strings. For example, if you want to pass key1=value1 and key2=value2 to httpbin.org/get, then you can use the following code:


##

>>> payload = {'key1': 'value1', 'key2': 'value2'}
>>> r = requests.get("http://httpbin.org/get", params=payload)
Copy after login

print out the URL , you can see that the URL has been encoded correctly:


>>> print(r.url)
http://httpbin.org/get?key2=value2&key1=value1
Copy after login

Note that keys with a value of None in the dictionary will not be added to the URL query string.

You can also pass in a list as a value:


>>> 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
Copy after login

Response content

We can read the content of the server response. Using the GitHub timeline as an example again:


>>> import requests
>>> r = requests.get('https://github.com/timeline.json')
>>> r.text
u'[{"repository":{"open_issues":0,"url":"https://github.com/...
Copy after login

Requests automatically decode content from the server. Most unicode character sets can be decoded seamlessly.

After a request is sent, Requests will make an educated guess about the encoding of the response based on the HTTP headers. When you access r.text, Requests uses its inferred text encoding. You can find out what encoding Requests uses, and be able to change it using the r.encoding property:


>>> r.encoding
'utf-8'
>>> r.encoding = 'ISO-8859-1'
Copy after login

If you change the encoding, whenever you access r.text , Request will use the new value of r.encoding. You may wish to change the encoding if special logic is used to calculate the encoding of the text. For example, HTTP and XML can specify encodings themselves. In this case, you should use r.content to find the encoding, and then set r.encoding to the corresponding encoding. This will allow r.text to be parsed using the correct encoding.

Requests can also use custom encoding if you need it. If you create your own encoding and register it with the codecs module, you can easily use the decoder name as the value of r.encoding and let Requests handle the encoding for you.

Binary response content

You can also access the request response body in bytes, for non-text requests:


>>> r.content
b'[{"repository":{"open_issues":0,"url":"https://github.com/...
Copy after login

Requests will automatically decode gzip and deflate transfer-encoded response data for you.

For example, to create an image from the binary data returned by the request, you can use the following code:


>>> from PIL import Image
>>> from io import BytesIO
>>> i = Image.open(BytesIO(r.content))
Copy after login

JSON response content

Requests also has a built-in JSON decoder to help you process JSON data:


>>> import requests
>>> r = requests.get('https://github.com/timeline.json')
>>> r.json()
[{u'repository': {u'open_issues': 0, u'url': 'https://github.com/...
Copy after login

If JSON decoding fails, r .json() will throw an exception. For example, if the response is 401 (Unauthorized), trying to access r.json() will throw a ValueError: No JSON object could be decoded exception.

It should be noted that successfully calling r.json() does not mean the success of the response. Some servers include a JSON object in the failure response (such as HTTP 500 error details). This JSON will be decoded and returned. To check if the request was successful, use r.raise_for_status() or check if r.status_code is what you expected.

Original response content

在罕见的情况下,你可能想获取来自服务器的原始套接字响应,那么你可以访问 r.raw。 如果你确实想这么干,那请你确保在初始请求中设置了 stream=True。具体你可以这么做:


>>> r = requests.get('https://github.com/timeline.json', stream=True)
>>> r.raw
<requests.packages.urllib3.response.HTTPResponse object at 0x101194810>
>>> r.raw.read(10)
&#39;\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\x03&#39;
Copy after login

但一般情况下,你应该以下面的模式将文本流保存到文件:


with open(filename, &#39;wb&#39;) as fd:
 for chunk in r.iter_content(chunk_size):
  fd.write(chunk)
Copy after login

使用 Response.iter_content 将会处理大量你直接使用 Response.raw 不得不处理的。 当流下载时,上面是优先推荐的获取内容方式。 Note that chunk_size can be freely adjusted to a number that may better fit your use cases.

定制请求头

如果你想为请求添加 HTTP 头部,只要简单地传递一个 dict 给 headers 参数就可以了。

例如,在前一个示例中我们没有指定 content-type:

>>> url = 'https://api.github.com/some/endpoint'
>>> headers = {'user-agent': 'my-app/0.0.1'}
>>> r = requests.get(url, headers=headers)

注意: 定制 header 的优先级低于某些特定的信息源,例如:

如果在 .netrc 中设置了用户认证信息,使用 headers= 设置的授权就不会生效。而如果设置了auth= 参数,``.netrc`` 的设置就无效了。

如果被重定向到别的主机,授权 header 就会被删除。

代理授权 header 会被 URL 中提供的代理身份覆盖掉。

在我们能判断内容长度的情况下,header 的 Content-Length 会被改写。

更进一步讲,Requests 不会基于定制 header 的具体情况改变自己的行为。只不过在最后的请求中,所有的 header 信息都会被传递进去。

注意: 所有的 header 值必须是 string、bytestring 或者 unicode。尽管传递 unicode header 也是允许的,但不建议这样做。

更加复杂的 POST 请求

通常,你想要发送一些编码为表单形式的数据——非常像一个 HTML 表单。要实现这个,只需简单地传递一个字典给 data 参数。你的数据字典在发出请求时会自动编码为表单形式:

>>> payload = {'key1': 'value1', 'key2': 'value2'}

>>> r = requests.post("http://httpbin.org/post", data=payload)
>>> print(r.text)
{
...
"form": {
"key2": "value2",
"key1": "value1"
},
...
}

你还可以为 data 参数传入一个元组列表。在表单中多个元素使用同一 key 的时候,这种方式尤其有效:

>>> payload = (('key1', 'value1'), ('key1', 'value2'))
>>> r = requests.post('http://httpbin.org/post', data=payload)
>>> print(r.text)
{
...
"form": {
"key1": [
"value1",
"value2"
]
},
...
}

很多时候你想要发送的数据并非编码为表单形式的。如果你传递一个 string 而不是一个 dict,那么数据会被直接发布出去。

例如,Github API v3 接受编码为 JSON 的 POST/PATCH 数据:

>>> import json
>>> url = 'https://api.github.com/some/endpoint'
>>> payload = {'some': 'data'}
>>> r = requests.post(url, data=json.dumps(payload))

此处除了可以自行对 dict 进行编码,你还可以使用 json 参数直接传递,然后它就会被自动编码。这是 2.4.2 版的新加功能:

>>> url = 'https://api.github.com/some/endpoint'
>>> payload = {'some': 'data'}
>>> r = requests.post(url, json=payload)

POST一个多部分编码(Multipart-Encoded)的文件

Requests 使得上传多部分编码文件变得很简单:

>>> url = 'http://httpbin.org/post'
>>> files = {'file': open('report.xls', 'rb')}
>>> r = requests.post(url, files=files)
>>> r.text
{
...
"files": {
"file": ""
},
...
}

你可以显式地设置文件名,文件类型和请求头:

>>> 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)
>>> r.text
{
...
"files": {
"file": " "
},
...
}

If you want, you can also send the string received as a file:

>>> url = 'http://httpbin.org/post'
>>> files = {'file': ('report.csv', 'some,data,to,send\nanother,row,to ,send\n')}

>>> r = requests.post(url, files=files)
>>> r.text
{
...
"files": {
"file": "some,data,to,send\\nanother,row,to,send\\n"
},
...
}

If you send a very large file as a multipart/form-data request, you may want to stream the request. By default, requests are not supported, but there is a third-party package requests-toolbelt that supports it. You can read the toolbelt documentation to learn how to use it.

Send multiple file references in one request Advanced Usage section.

WARNING

We strongly recommend that you open the file in binary mode. This is because Requests may try to provide you with a Content-Length header, and when it does so, this value will be set to the number of bytes in the file. If you open the file in text mode, errors may occur.

Response status code

We can detect the response status code:

>>> r = requests.get('http://httpbin.org/get ')
>>> r.status_code
200

For easy reference, Requests also comes with a built-in status code query object:

>> > r.status_code == requests.codes.ok
True

If an error request is sent (a 4XX client error, or a 5XX server error response), we can pass Response.raise_for_status() To throw an exception:

>>> bad_r = requests.get('http://httpbin.org/status/404')
>>> bad_r.status_code
404
>>> bad_r.raise_for_status()
Traceback (most recent call last):
File "requests/models.py", line 832, in raise_for_status
raise http_error
requests.exceptions.HTTPError: 404 Client Error

However, since the status_code of r in our example is 200, when we call raise_for_status(), we get:

> ;>> r.raise_for_status()
None

Everything is quite harmonious.

Response headers

We can view the server response headers displayed in the form of a Python dictionary:

>>> r.headers
{
'content-encoding': 'gzip',
'transfer-encoding': 'chunked',
'connection': 'close',
'server': 'nginx/1.0.4',
'x-runtime': '148ms',
'etag': '"e1ca502697e5c9317743dc078f67693f"',
'content-type': 'application/json'
}

But This dictionary is special: it is only for HTTP headers. According to RFC 2616, HTTP headers are case-insensitive.

Therefore, we can access these response header fields using any uppercase form:

>>> r.headers['Content-Type']
'application/json '
>>> r.headers.get('content-type')
'application/json'

It also has a special point, that is, the server can accept it multiple times For the same header, use different values ​​every time. But Requests will combine them so that they can be represented by a mapping, see RFC 7230:

A recipient MAY combine multiple header fields with the same field name into one "field-name: field-value " pair, without changing the semantics of the message, by appending each subsequent field value to the combined field value in order, separated by a comma.

The receiver can combine multiple header fields with the same name, They are combined into a "field-name: field-value" pair, and each subsequent field value is appended to the combined field value in turn, separated by commas, without changing the semantics of the information.

Cookie

If a response contains some cookies, you can quickly access them:

>>> url = 'http://example.com/some/cookie/setting/url'
>>> r = requests.get(url)
>>> r.cookies['example_cookie_name']
'example_cookie_value'
要想发送你的cookies到服务器,可以使用 cookies 参数:

>>> url = 'http://httpbin.org/cookies'
>>> cookies = dict(cookies_are='working')

>>> r = requests.get(url, cookies=cookies)
>>> r.text
'{"cookies": {"cookies_are": "working"}}'

Cookie 的返回对象为 RequestsCookieJar,它的行为和字典类似,但界面更为完整,适合跨域名跨路径使用。你还可以把 Cookie Jar 传到 Requests 中:


>>> jar = requests.cookies.RequestsCookieJar()
>>> jar.set(&#39;tasty_cookie&#39;, &#39;yum&#39;, domain=&#39;httpbin.org&#39;, path=&#39;/cookies&#39;)
>>> jar.set(&#39;gross_cookie&#39;, &#39;blech&#39;, domain=&#39;httpbin.org&#39;, path=&#39;/elsewhere&#39;)
>>> url = &#39;http://httpbin.org/cookies&#39;
>>> r = requests.get(url, cookies=jar)
>>> r.text
&#39;{"cookies": {"tasty_cookie": "yum"}}&#39;
Copy after login

重定向与请求历史

默认情况下,除了 HEAD, Requests 会自动处理所有重定向。

可以使用响应对象的 history 方法来追踪重定向。

Response.history 是一个 Response 对象的列表,为了完成请求而创建了这些对象。这个对象列表按照从最老到最近的请求进行排序。

例如,Github 将所有的 HTTP 请求重定向到 HTTPS:


>>> r = requests.get(&#39;http://github.com&#39;)
>>> r.url
&#39;https://github.com/&#39;
>>> r.status_code
200
>>> r.history
[<Response [301]>]
Copy after login

如果你使用的是GET、OPTIONS、POST、PUT、PATCH 或者 DELETE,那么你可以通过 allow_redirects 参数禁用重定向处理:


>>> r = requests.get(&#39;http://github.com&#39;, allow_redirects=False)
>>> r.status_code
301
>>> r.history
[]
Copy after login

如果你使用了 HEAD,你也可以启用重定向:


>>> r = requests.head(&#39;http://github.com&#39;, allow_redirects=True)
>>> r.url
&#39;https://github.com/&#39;
>>> r.history
[<Response [301]>]
Copy after login

超时

你可以告诉 requests 在经过以 timeout 参数设定的秒数时间之后停止等待响应。基本上所有的生产代码都应该使用这一参数。如果不使用,你的程序可能会永远失去响应:


>>> requests.get(&#39;http://github.com&#39;, timeout=0.001)
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
requests.exceptions.Timeout: HTTPConnectionPool(host=&#39;github.com&#39;, port=80): Request timed out. (timeout=0.001)
Copy after login

注意

timeout 仅对连接过程有效,与响应体的下载无关。 timeout 并不是整个下载响应的时间限制,而是如果服务器在 timeout 秒内没有应答,将会引发一个异常(更精确地说,是在timeout 秒内没有从基础套接字上接收到任何字节的数据时)If no timeout is specified explicitly, requests do not time out.

错误与异常

遇到网络问题(如:DNS 查询失败、拒绝连接等)时,Requests 会抛出一个 ConnectionError 异常。

如果 HTTP 请求返回了不成功的状态码, Response.raise_for_status() 会抛出一个 HTTPError 异常。

若请求超时,则抛出一个 Timeout 异常。

若请求超过了设定的最大重定向次数,则会抛出一个 TooManyRedirects 异常。

所有Requests显式抛出的异常都继承自 requests.exceptions.RequestException 。

The above is the detailed content of Quick start introduction to python requests. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template