gpt4 book ai didi

python - 如何从原始 HTTP 请求字节流构建 webob.Request 或 WSGI 'environ' 字典?

转载 作者:太空宇宙 更新时间:2023-11-03 14:35:36 25 4
gpt4 key购买 nike

假设我有一个包含以下内容的字节流:

POST /mum/ble?q=huhContent-Length: 18Content-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=huhContent-Length: 18Content-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

基本上,我们需要对请求处理程序进行子类化,以伪造通常由服务器执行的构造过程(rfilewfile 从套接字构建到客户端等)。我认为这还不够完整,但应该很接近了,我希望它对您有所帮助!

请注意,我还修复了您的示例 HTTP 请求:如果原始请求行末尾没有 HTTP/1.0 或 1.1,则 POST 被认为是错误的- 在 handler.wfile 上形成并导致异常和结果错误消息。

关于python - 如何从原始 HTTP 请求字节流构建 webob.Request 或 WSGI 'environ' 字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1010103/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com