jeudi 28 janvier 2016

How do I split recieving requests and sending responses into two functions using Python's `wsgiref` API ?`

I'm writing an extensible web framework in Python. My abstract base class for the server defines a receive and a send method. The implemented server should return a Request object when receive is called, and send should take a Response object and send it to the client. The problem is that I have to build my request from the WSGI app's environment and translate my response into a valid WSGI response object. However I fail when trying to implement this class for my WSGI server because, as far as I know, WSGI applications must do both tasks at the same time.

I have the code for my methods, but how can I access environ and start_response from those ?

Here's the code:

class WSGIServer(Server):
    def receive(self):
        url = environ['PATH_INFO']

        method_name = environ['REQUEST_METHOD']
        method = Method[method_name]

        if method is Method.GET:
            query = environ['QUERY_STRING']
        else:
            size = int(environ.get('CONTENT_LENGTH', 0))
            query = environ['wsgi.input'].read(size).decode('UTF-8')

        args = {}

        for arg in filter(bool, query.split('&')):
            name, val = arg.split('=')
            args[name] = val

        headers = Headers([])
        request = Request(url, method, headers, args)

        return request

    def send(self, response):
        start_response(response.status, list(response.headers.items()))
        wsgi_response = [response.page.as_string().encode('utf-8')]

        return wsgi_response

Thanks.




Aucun commentaire:

Enregistrer un commentaire