How to create webob.Request or WSGI 'environment' dict from raw HTTP request stream?

Suppose I have a stream of bytes 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 any way to create a WSGI-style dict from it?

Hopefully I missed the simple 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 __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"]
+3
source share
1 answer

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.

+5

Source: https://habr.com/ru/post/1710725/


All Articles