假设我有一个字节流,其中包含以下内容:
POST /mum/ble?q=huh Content-Length: 18 Content-Type: application/json; charset="utf-8" Host: localhost:80 ["do", "re", "mi"]
有没有办法从中产生出WSGI风格的“环境”指示?
希望我忽略了一个简单的答案,它与相反的操作一样容易实现.
考虑:
>>> import json
>>> from webob import Request
>>> r = Request.blank('/mum/ble?q=huh')
>>> r.method = 'POST'
>>> r.content_type = 'application/json'
>>> r.charset = 'utf-8'
>>> r.body = json.dumps(['do', 're', 'mi'])
>>> print str(r) # Request's __str__ method gives raw HTTP bytes back!
POST /mum/ble?q=huh Content-Length: 18 Content-Type: application/json; charset="utf-8" Host: localhost:80 ["do", "re", "mi"]
解决方法:
为此目的,重用Python的标准库代码有些棘手(它并非旨在以这种方式重用!-),但应该是可行的,例如:
import cStringIO
from wsgiref import simple_server, util
input_string = """POST /mum/ble?q=huh HTTP/1.0
Content-Length: 18
Content-Type: application/json; charset="utf-8"
Host: localhost:80
["do", "re", "mi"]
"""
class FakeHandler(simple_server.WSGIRequestHandler):
def __init__(self, rfile):
self.rfile = rfile
self.wfile = cStringIO.StringIO() # for error msgs
self.server = self
self.base_environ = {}
self.client_address = ['?', 80]
self.raw_requestline = self.rfile.readline()
self.parse_request()
def getenv(self):
env = self.get_environ()
util.setup_testing_defaults(env)
env['wsgi.input'] = self.rfile
return env
handler = FakeHandler(rfile=cStringIO.StringIO(input_string))
wsgi_env = handler.getenv()
print wsgi_env
基本上,我们需要对请求处理程序进行子类化,以伪造通常由服务器为其执行的构造过程(从套接字到客户端构建的rfile和wfile等).我认为这还不太完整,但是应该接近,希望对您有帮助!
请注意,我还修复了示例HTTP请求:在原始请求行的末尾没有HTTP / 1.0或1.1的情况下,POST被视为格式不正确,并在handler.wfile上导致异常和生成的错误消息.