加载中...

11.1 作为客户端与HTTP服务交互


问题

你需要通过HTTP协议以客户端的方式访问多种服务。例如,下载数据或者与基于REST的API进行交互。

解决方案

对于简单的事情来说,通常使用 <span class="pre" style="box-sizing: border-box;">urllib.request</span> 模块就够了。例如,发送一个简单的HTTP GET请求到远程的服务上,可以这样做:

  1. from urllib import request, parse
  2. # Base URL being accessed
  3. url = 'http://httpbin.org/get'
  4. # Dictionary of query parameters (if any)
  5. parms = {
  6. 'name1' : 'value1',
  7. 'name2' : 'value2'
  8. }
  9. # Encode the query string
  10. querystring = parse.urlencode(parms)
  11. # Make a GET request and read the response
  12. u = request.urlopen(url+'?' + querystring)
  13. resp = u.read()

如果你需要使用POST方法在请求主体中发送查询参数,可以将参数编码后作为可选参数提供给<span class="pre" style="box-sizing: border-box;">urlopen()</span> 函数,就像这样:

  1. from urllib import request, parse
  2. # Base URL being accessed
  3. url = 'http://httpbin.org/post'
  4. # Dictionary of query parameters (if any)
  5. parms = {
  6. 'name1' : 'value1',
  7. 'name2' : 'value2'
  8. }
  9. # Encode the query string
  10. querystring = parse.urlencode(parms)
  11. # Make a POST request and read the response
  12. u = request.urlopen(url, querystring.encode('ascii'))
  13. resp = u.read()

如果你需要在发出的请求中提供一些自定义的HTTP头,例如修改 <span class="pre" style="box-sizing: border-box;">user-agent</span> 字段,可以创建一个包含字段值的字典,并创建一个Request实例然后将其传给 <span class="pre" style="box-sizing: border-box;">urlopen()</span> ,如下:

  1. from urllib import request, parse
  2. ...
  3. # Extra headers
  4. headers = {
  5. 'User-agent' : 'none/ofyourbusiness',
  6. 'Spam' : 'Eggs'
  7. }
  8. req = request.Request(url, querystring.encode('ascii'), headers=headers)
  9. # Make a request and read the response
  10. u = request.urlopen(req)
  11. resp = u.read()

如果需要交互的服务比上面的例子都要复杂,也许应该去看看 requests 库(https://pypi.python.org/pypi/requests)。例如,下面这个示例采用requests库重新实现了上面的操作:

  1. import requests
  2. # Base URL being accessed
  3. url = 'http://httpbin.org/post'
  4. # Dictionary of query parameters (if any)
  5. parms = {
  6. 'name1' : 'value1',
  7. 'name2' : 'value2'
  8. }
  9. # Extra headers
  10. headers = {
  11. 'User-agent' : 'none/ofyourbusiness',
  12. 'Spam' : 'Eggs'
  13. }
  14. resp = requests.post(url, data=parms, headers=headers)
  15. # Decoded text returned by the request
  16. text = resp.text

关于requests库,一个值得一提的特性就是它能以多种方式从请求中返回响应结果的内容。从上面的代码来看, <span class="pre" style="box-sizing: border-box;">resp.text</span> 带给我们的是以Unicode解码的响应文本。但是,如果去访问 <span class="pre" style="box-sizing: border-box;">resp.content</span>,就会得到原始的二进制数据。另一方面,如果访问 <span class="pre" style="box-sizing: border-box;">resp.json</span> ,那么就会得到JSON格式的响应内容。

下面这个示例利用 <span class="pre" style="box-sizing: border-box;">requests</span> 库发起一个HEAD请求,并从响应中提取出一些HTTP头数据的字段:

  1. import requests
  2. resp = requests.head('http://www.python.org/index.html')
  3. status = resp.status_code
  4. last_modified = resp.headers['last-modified']
  5. content_type = resp.headers['content-type']
  6. content_length = resp.headers['content-length']
  7. Here is a requests example that executes a login into the Python Package index using
  8. basic authentication:
  9. import requests
  10. resp = requests.get('http://pypi.python.org/pypi?:action=login',
  11. auth=('user','password'))
  12. Here is an example of using requests to pass HTTP cookies from one request to the
  13. next:
  14. import requests
  15. # First request
  16. resp1 = requests.get(url)
  17. ...
  18. # Second requests with cookies received on first requests
  19. resp2 = requests.get(url, cookies=resp1.cookies)
  20. Last, but not least, here is an example of using requests to upload content:
  21. import requests
  22. url = 'http://httpbin.org/post'
  23. files = { 'file': ('data.csv', open('data.csv', 'rb')) }
  24. r = requests.post(url, files=files)

讨论

对于真的很简单HTTP客户端代码,用内置的 <span class="pre" style="box-sizing: border-box;">urllib</span> 模块通常就足够了。但是,如果你要做的不仅仅只是简单的GET或POST请求,那就真的不能再依赖它的功能了。这时候就是第三方模块比如<span class="pre" style="box-sizing: border-box;">requests</span> 大显身手的时候了。

例如,如果你决定坚持使用标准的程序库而不考虑像 <span class="pre" style="box-sizing: border-box;">requests</span> 这样的第三方库,那么也许就不得不使用底层的 <span class="pre" style="box-sizing: border-box;">http.client</span> 模块来实现自己的代码。比方说,下面的代码展示了如何执行一个HEAD请求:

  1. from http.client import HTTPConnection
  2. from urllib import parse
  3. c = HTTPConnection('www.python.org', 80)
  4. c.request('HEAD', '/index.html')
  5. resp = c.getresponse()
  6. print('Status', resp.status)
  7. for name, value in resp.getheaders():
  8. print(name, value)

同样地,如果必须编写涉及代理、认证、cookies以及其他一些细节方面的代码,那么使用 <span class="pre" style="box-sizing: border-box;">urllib</span> 就显得特别别扭和啰嗦。比方说,下面这个示例实现在Python包索引上的认证:

  1. import urllib.request
  2. auth = urllib.request.HTTPBasicAuthHandler()
  3. auth.add_password('pypi','http://pypi.python.org','username','password')
  4. opener = urllib.request.build_opener(auth)
  5. r = urllib.request.Request('http://pypi.python.org/pypi?:action=login')
  6. u = opener.open(r)
  7. resp = u.read()
  8. # From here. You can access more pages using opener
  9. ...

坦白说,所有的这些操作在 <span class="pre" style="box-sizing: border-box;">requests</span> 库中都变得简单的多。

在开发过程中测试HTTP客户端代码常常是很令人沮丧的,因为所有棘手的细节问题都需要考虑(例如cookies、认证、HTTP头、编码方式等)。要完成这些任务,考虑使用httpbin服务(http://httpbin.org)。这个站点会接收发出的请求,然后以JSON的形式将相应信息回传回来。下面是一个交互式的例子:

  1. >>> import requests
  2. >>> r = requests.get('http://httpbin.org/get?name=Dave&n=37',
  3. ... headers = { 'User-agent': 'goaway/1.0' })
  4. >>> resp = r.json
  5. >>> resp['headers']
  6. {'User-Agent': 'goaway/1.0', 'Content-Length': '', 'Content-Type': '',
  7. 'Accept-Encoding': 'gzip, deflate, compress', 'Connection':
  8. 'keep-alive', 'Host': 'httpbin.org', 'Accept': '*/*'}
  9. >>> resp['args']
  10. {'name': 'Dave', 'n': '37'}
  11. >>>

在要同一个真正的站点进行交互前,先在 httpbin.org 这样的网站上做实验常常是可取的办法。尤其是当我们面对3次登录失败就会关闭账户这样的风险时尤为有用(不要尝试自己编写HTTP认证客户端来登录你的银行账户)。

尽管本节没有涉及, <span class="pre" style="box-sizing: border-box;">request</span> 库还对许多高级的HTTP客户端协议提供了支持,比如OAuth。<span class="pre" style="box-sizing: border-box;">requests</span> 模块的文档(http://docs.python-requests.org)质量很高(坦白说比在这短短的一节的篇幅中所提供的任何信息都好),可以参考文档以获得更多地信息。


还没有评论.