python 解析 HTTP 响应 (字符串)
我正在使用Python 2.7,想要解析我从一个文本文件中提取出来的字符串格式的HTTP响应字段。有没有什么简单的方法可以做到这一点?我可以用BaseHTTPServer来解析请求,但找不到处理响应的办法。
我手头的响应格式很标准,像下面这样:
HTTP/1.1 200 OK
Date: Thu, Jul 3 15:27:54 2014
Content-Type: text/xml; charset="utf-8"
Connection: close
Content-Length: 626
提前谢谢你,
2 个回答
-8
你可能想考虑使用python-requests这个库。
链接:http://docs.python-requests.org/en/latest/
这里有一个来自http://dancallahan.info/journal/python-requests/的例子。
考虑到你的响应符合HTTP的标准。
这看起来像是你想做的事情吗?
>>> import requests
>>> url = 'http://example.test/'
>>> response = requests.get(url)
>>> response.status_code
200
>>> response.headers['content-type']
'text/html; charset=utf-8'
>>> response.content
u'Hello, world!'
31
你可能会觉得这些信息有用,但要记住,HTTPResponse 这个东西并不是为了让用户直接创建的。
另外要注意,你的响应字符串中的内容长度头信息可能不再有效(这取决于你是如何获取这些响应的)。这意味着调用 HTTPResponse.read() 时,传入的值需要大于内容的实际大小,才能把所有内容都读取到。
在 Python 2 中,可以这样运行。
from httplib import HTTPResponse
from StringIO import StringIO
http_response_str = """HTTP/1.1 200 OK
Date: Thu, Jul 3 15:27:54 2014
Content-Type: text/xml; charset="utf-8"
Connection: close
Content-Length: 626"""
class FakeSocket():
def __init__(self, response_str):
self._file = StringIO(response_str)
def makefile(self, *args, **kwargs):
return self._file
source = FakeSocket(http_response_str)
response = HTTPResponse(source)
response.begin()
print "status:", response.status
print "single header:", response.getheader('Content-Type')
print "content:", response.read(len(http_response_str)) # the len here will give a 'big enough' value to read the whole content
在 Python 3 中,HTTPResponse
是从 http.client
导入的,并且需要解析的响应需要进行字节编码。根据数据的来源,这个编码可能已经完成,或者需要你手动调用。
from http.client import HTTPResponse
from io import BytesIO
http_response_str = """HTTP/1.1 200 OK
Date: Thu, Jul 3 15:27:54 2014
Content-Type: text/xml; charset="utf-8"
Connection: close
Content-Length: 626
teststring"""
http_response_bytes = http_response_str.encode()
class FakeSocket():
def __init__(self, response_bytes):
self._file = BytesIO(response_bytes)
def makefile(self, *args, **kwargs):
return self._file
source = FakeSocket(http_response_bytes)
response = HTTPResponse(source)
response.begin()
print( "status:", response.status)
# status: 200
print( "single header:", response.getheader('Content-Type'))
# single header: text/xml; charset="utf-8"
print( "content:", response.read(len(http_response_str)))
# content: b'teststring'