httplib(现在是http.client)和朋友们都有conn.getresponse()和HTTPResponse类,但是conn.getrequest()和HTTPRequest类的服务器端操作似乎缺乏.
我知道BaseHTTPServer和BaseHTTPRequestHandler可以执行此功能,但它们不会公开这些方法以在模块外部使用.
基本上我想要的是BaseHTTPRequestHandler #parse_request是一个静态方法,它返回一个HTTPRequest对象,而不是填充成员变量.
Jeff,为了启用解析,我创建了一个基本HTTP请求处理程序的小九行子类:
from BaseHTTPServer import BaseHTTPRequestHandler from StringIO import StringIO class HTTPRequest(BaseHTTPRequestHandler): def __init__(self, request_text): self.rfile = StringIO(request_text) self.raw_requestline = self.rfile.readline() self.error_code = self.error_message = None self.parse_request() def send_error(self, code, message): self.error_code = code self.error_message = message
您现在可以在其中包含一个包含HTTP请求文本的字符串,并通过实例化此类来解析它:
# Simply instantiate this class with the request text request = HTTPRequest(request_text) print request.error_code # None (check this first) print request.command # "GET" print request.path # "/who/ken/trust.html" print request.request_version # "HTTP/1.1" print len(request.headers) # 3 print request.headers.keys() # ['accept-charset', 'host', 'accept'] print request.headers['host'] # "cm.bell-labs.com" # Parsing can result in an error code and message request = HTTPRequest('GET\r\nHeader: Value\r\n\r\n') print request.error_code # 400 print request.error_message # "Bad request syntax ('GET')"