Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/284.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python是否有用于解析HTTP请求和响应的模块?_Python_Http_Parsing - Fatal编程技术网

Python是否有用于解析HTTP请求和响应的模块?

Python是否有用于解析HTTP请求和响应的模块?,python,http,parsing,Python,Http,Parsing,httplib(现在是http.client)和friends都有conn.getresponse()和一个HTTPResponse类,但似乎缺少conn.getrequest()和HTTPRequest类的服务器端操作 我知道BaseHTTPServer和BaseHTTPRequestHandler可以执行此功能,但它们不会公开这些方法以供模块外使用 基本上,我希望BaseHTTPRequestHandler#parse_request是一个静态方法,返回HTTPRequest对象,而不是填充

httplib(现在是http.client)和friends都有conn.getresponse()和一个HTTPResponse类,但似乎缺少conn.getrequest()和HTTPRequest类的服务器端操作

我知道BaseHTTPServer和BaseHTTPRequestHandler可以执行此功能,但它们不会公开这些方法以供模块外使用


基本上,我希望BaseHTTPRequestHandler#parse_request是一个静态方法,返回HTTPRequest对象,而不是填充成员变量。

对于服务器端处理,您希望看到类似的内容


WSGI标准将请求解析为一个包含所有相关头和元素的简单字典。

您可能会发现它很有用。Pylons、Turbogears和Bfg等框架将其作为api的一部分。不过,它确实是在假设您在WSGI下工作的情况下运行的

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')"
这与解析您自己的HTTPRequest相结合非常方便。