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

多个文件

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

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)