以 HTTP POST 方法及其相应的 Requests 函数为背景的 Python Requests 模块文档

Section 95.1: 简单 Post

from requests import post

foo = post('http://httpbin.org/post', data = {'key':'value'})

将执行简单的 HTTP POST 操作。发布的数据可以是各种格式,但最常见的是键值对。

标题

可以查看标题:

print(foo.headers)

响应示例:

{'Content-Length': '439', 'X-Processed-Time': '0.000802993774414', 'X-Powered-By': 'Flask', 'Server': 'meinheld/0.6.1', 'Connection': 'keep-alive', 'Via': '1.1 vegur', 'Access-Control-Allow-Credentials': 'true', 'Date': 'Sun, 21 May 2017 20:56:05 GMT', 'Access-Control-Allow-Origin': '*', 'Content-Type': 'application/json'}

标题也可以在发布前准备好:

headers = {'Cache-Control':'max-age=0',
           'Upgrade-Insecure-Requests':'1',
           'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36',
           'Content-Type':'application/x-www-form-urlencoded',
           'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
           'Referer':'https://www.groupon.com/signup',
           'Accept-Encoding':'gzip, deflate, br',
           'Accept-Language':'es-ES,es;q=0.8'
}

foo = post('http://httpbin.org/post', headers=headers, data = {'key':'value'})

编码

编码的设置和查看方法大致相同:

print(foo.encoding)
'utf-8'
foo.encoding = 'ISO-8859-1'

SSL 验证

请求默认验证域的 SSL 证书。这可以被覆盖:

foo = post('http://httpbin.org/post', data = {'key':'value'}, verify=False)

重定向

将遵循任何重定向(如从 http 到 https),也可以更改:

foo = post('http://httpbin.org/post', data = {'key':'value'}, allow_redirects=False)

如果发布操作已被重定向,则可以访问该值:

print(foo.url)

可查看全部重定向历史记录:

print(foo.history)

Section 95.2: 表格编码数据

from requests import post

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

foo = post('http://httpbin.org/post', data=payload)

要通过 post 操作传递表单编码数据,必须将数据结构为字典,并作为数据参数提供。

如果数据不想被表单编码,只需在数据参数中传递一个字符串或整数即可。

向 json 参数提供字典,以便 Requests 自动格式化数据:

from requests import post

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

foo = post('http://httpbin.org/post', json=payload)

Section 95.3: 上传文件

有了 Requests 模块,只需提供文件句柄,而不是用 .read()获取的内容:

from requests import post

files = {'file' : open('data.txt', 'rb')}

foo = post('http://http.org/post', files=files)

还可以设置文件名、内容类型和标题:

files = {'file': ('report.xls', open('report.xls', 'rb'), 'application/vnd.ms-excel', {'Expires': '0'})}

foo = requests.post('http://httpbin.org/post', files=files)

只要作为文件参数提供,字符串也可以作为文件发送。

多个文件

提供多个文件的方式与提供一个文件的方式基本相同:

multiple_files = [
  ('images', ('foo.png', open('foo.png', 'rb'), 'image/png')),
  ('images', ('bar.png', open('bar.png', 'rb'), 'image/png'))]

foo = post('http://httpbin.org/post', files=multiple_files)

Section 95.4: 响应

响应代码可通过后置操作查看:

from requests import post

foo = post('http://httpbin.org/post', data={'data' : 'value'})

print(foo.status_code)

返回的数据

访问返回的数据

foo = post('http://httpbin.org/post', data={'data' : 'value'})
print(foo.text)

原始响应

在需要访问底层 urllib3 的 response.HTTPResponse 对象的情况下,可以通过以下方法实现:

foo = post('http://httpbin.org/post', data={'data' : 'value'})
res = foo.raw

print(res.read())

Section 95.5: 认证

简单 HTTP 身份验证

简单 HTTP 身份验证可通过以下方式实现:

from requests import post

foo = post('http://natas0.natas.labs.overthewire.org', auth=('natas0', 'natas0'))

从技术上讲,这是以下内容的简称:

from requests import post
from requests.auth import HTTPBasicAuth

foo = post('http://natas0.natas.labs.overthewire.org', auth=HTTPBasicAuth('natas0', 'natas0'))

HTTP摘要验证

HTTP 摘要身份验证的方式非常相似,但 Requests 为此提供了一个不同的对象:

from requests import post
from requests.auth import HTTPDigestAuth

foo = post('http://natas0.natas.labs.overthewire.org', auth=HTTPDigestAuth('natas0', 'natas0'))

自定义身份验证

在某些情况下,内置的身份验证机制可能还不够,请看下面的例子:

如果发件人拥有正确的用户代理字符串、特定的头值,并通过 HTTP 基本身份验证提供了正确的凭证,服务器就会被配置为接受身份验证。为此,应准备一个自定义身份验证类,它是 AuthBase 的子类,而 AuthBase 是请求身份验证实现的基础:

from requests.auth import AuthBase
from requests.auth import _basic_auth_str
from requests._internal_utils import to_native_string

class CustomAuth(AuthBase):
  def __init__(self, secret_header, user_agent , username, password):
    # setup any auth-related data here
    self.secret_header = secret_header
    self.user_agent = user_agent
    self.username = username
    self.password = password

  def __call__(self, r):
    # modify and return the request
    r.headers['X-Secret'] = self.secret_header
    r.headers['User-Agent'] = self.user_agent
    r.headers['Authorization'] = _basic_auth_str(self.username, self.password)

    return r

然后就可以用下面的代码来实现:

foo = get('http://test.com/admin', auth=CustomAuth('SecretHeader', 'CustomUserAgent', 'user', 'password' ))

Section 95.6: 代理

每个请求 POST 操作都可配置为使用网络代理

HTTP/S 代理

from requests import post

proxies = {
  'http': 'http://192.168.0.128:3128',
  'https': 'http://192.168.0.127:1080',
}

foo = requests.post('http://httpbin.org/post', proxies=proxies)

HTTP Basic 身份验证可以通过这种方式提供:

proxies = {'http': 'http://user:pass@192.168.0.128:312'}
foo = requests.post('http://httpbin.org/post', proxies=proxies)

SOCKS 代理

使用 socks 代理需要第三方依赖请求[socks],安装后使用 socks 代理的方式与 HTTPBasicAuth 非常相似:

proxies = {
  'http': 'socks5://user:pass@host:port',
  'https': 'socks5://user:pass@host:port'
}

foo = requests.post('http://httpbin.org/post', proxies=proxies)