当前位置: 首页 > 深入 Python > HTTP Web 服务 > 综述 | << >> | ||||
深入 Python从 Python 新手到专家 |
您已经了解了构建智能 HTTP Web 服务客户端的所有组件。现在让我们看看它们是如何组合在一起的。
此函数在 openanything.py 中定义。
def openAnything(source, etag=None, lastmodified=None, agent=USER_AGENT): # non-HTTP code omitted for brevity if urlparse.urlparse(source)[0] == 'http':# open URL with urllib2 request = urllib2.Request(source) request.add_header('User-Agent', agent)
if etag: request.add_header('If-None-Match', etag)
if lastmodified: request.add_header('If-Modified-Since', lastmodified)
request.add_header('Accept-encoding', 'gzip')
opener = urllib2.build_opener(SmartRedirectHandler(), DefaultErrorHandler())
return opener.open(request)
![]()
此函数在 openanything.py 中定义。
def fetch(source, etag=None, last_modified=None, agent=USER_AGENT): '''Fetch data and metadata from a URL, file, stream, or string''' result = {} f = openAnything(source, etag, last_modified, agent)result['data'] = f.read()
if hasattr(f, 'headers'): # save ETag, if the server sent one result['etag'] = f.headers.get('ETag')
# save Last-Modified header, if the server sent one result['lastmodified'] = f.headers.get('Last-Modified')
if f.headers.get('content-encoding', '') == 'gzip':
# data came back gzip-compressed, decompress it result['data'] = gzip.GzipFile(fileobj=StringIO(result['data']])).read() if hasattr(f, 'url'):
result['url'] = f.url result['status'] = 200 if hasattr(f, 'status'):
result['status'] = f.status f.close() return result
>>> import openanything >>> useragent = 'MyHTTPWebServicesApp/1.0' >>> url = 'https://diveintopythonbook.pythonlang.cn/redir/example301.xml' >>> params = openanything.fetch(url, agent=useragent)>>> params
{'url': 'http://diveintomark.org/xml/atom.xml', 'lastmodified': 'Thu, 15 Apr 2004 19:45:21 GMT', 'etag': '"e842a-3e53-55d97640"', 'status': 301, 'data': '<?xml version="1.0" encoding="iso-8859-1"?> <feed version="0.3" <-- rest of data omitted for brevity -->'} >>> if params['status'] == 301:
... url = params['url'] >>> newparams = openanything.fetch( ... url, params['etag'], params['lastmodified'], useragent)
>>> newparams {'url': 'http://diveintomark.org/xml/atom.xml', 'lastmodified': None, 'etag': '"e842a-3e53-55d97640"', 'status': 304, 'data': ''}
![]()
![]() |
第一次获取资源时,您没有 ETag 哈希值或 Last-Modified 日期,因此您将省略它们。(它们是可选参数。) |
![]() |
您得到的是一个包含几个有用标头、HTTP 状态码和从服务器返回的实际数据的字典。openanything 在内部处理 gzip 压缩;您在此级别无需关心这一点。 |
![]() |
如果您收到 301 状态码,则表示永久重定向,您需要将 URL 更新为新地址。 |
![]() |
第二次获取相同资源时,您拥有各种要传递回的信息:(可能已更新的)URL、上次的 ETag、上次的 Last-Modified 日期,当然还有您的 User-Agent。 |
![]() |
您得到的是一个字典,但数据没有改变,因此您只得到一个 304 状态码,没有数据。 |
<< 处理压缩数据 |
| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | |
总结 >> |