如何构建 webob.Request 或 WSGI“环境” 来自原始 HTTP 请求字节流的字典?
假设我有一个字节流,其中包含以下内容:
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"]
Suppose I have a byte stream with the following in it:
POST /mum/ble?q=huh Content-Length: 18 Content-Type: application/json; charset="utf-8" Host: localhost:80 ["do", "re", "mi"]
Is there a way to produce an WSGI-style 'environ' dict from it?
Hopefully, I've overlooked an easy answer, and it is as easy to achieve as the opposite operation.
Consider:
>>> 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"]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
为此目的重用 Python 的标准库代码有点棘手(它不是为以这种方式重用而设计的!-),但应该是可行的,例如:
基本上,我们需要子类化请求处理程序以伪造通常的构造过程由服务器执行(从套接字到客户端构建的
rfile
和wfile
,等等)。 我认为这还不太完整,但应该很接近,我希望它能有所帮助!请注意,我还修复了您的示例 HTTP 请求:原始请求行末尾没有
HTTP/1.0
或 1.1,POST
被视为格式不正确,并且在handler.wfile
上导致异常和错误消息。Reusing Python's standard library code for the purpose is a bit tricky (it was not designed to be reused that way!-), but should be doable, e.g:
Basically, we need to subclass the request handler to fake out the construction process that's normally performed for it by the server (
rfile
andwfile
built from the socket to the client, and so on). This isn't quite complete, I think, but should be close and I hope it proves helpful!Note that I've also fixed your example HTTP request: without an
HTTP/1.0
or 1.1 at the end of the raw request line, aPOST
is considered ill-formed and causes an exception and a resulting error message onhandler.wfile
.