Python有一个用于解析HTTP请求和响应的模块吗? [英] Does Python have a module for parsing HTTP requests and responses?

查看:117
本文介绍了Python有一个用于解析HTTP请求和响应的模块吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

httplib (now http.client) and friends all have conn.getresponse() and an HTTPResponse class, but the server-side operations of conn.getrequest() and an HTTPRequest class seem to be lacking.

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

I understand that BaseHTTPServer and BaseHTTPRequestHandler can perform this functionality, but they don't expose these methods for use outside of the module.

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

Essentially what I want is BaseHTTPRequestHandler#parse_request to be a static method that returns an HTTPRequest object rather than populating member variables.

推荐答案

Jeff,启用解析我创建了一个基本HTTP请求处理程序的小九行子类:

Jeff, to enable parsing I create a small nine-line subclass of the base HTTP request handler:

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请求的文本,并通过实例化此类来解析它:

You can now take a string with the text of an HTTP request inside and parse it by instantiating this class:

# 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')"

这篇关于Python有一个用于解析HTTP请求和响应的模块吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆