Quickly write custom wsgi dispatcher

</> wsgi

Now a days I am working on an angular based application that interacts with a python based web server over an api. I hired some freelancers to work on that application with me. Issue comes when they don't wanna setup full dev environment on their system, ofcourse they will not get paid for it. Which our application architecture doesn't allow.

As a solution, I wrote a small wsgi script for development purpose only. I am using flask to serve static files. which you can change with anything, and using paste.proxy to proxy api requests to backend server.

In my case all POST requests are meant for backend server and all GET should be fulfilled by local files. Here is how my dispatcher looks like:

class RequestMethodDispatcher(object):
    def __init__(self, main_app, config):
        # Here config is a dict with key as a request
        # method and value as wsgi app.
        self.main_app = main_app
        self.config = config

    def get_application(self, environ):
        # Do your dispatcher magic here.
        return self.config.get(
            environ['REQUEST_METHOD'], self.main_app
        )

    def __call__(self, environ, start_response):
        app = self.get_application(environ)
        return app(environ, start_response)

Here is how this dispatcher is used:

from flask import Flask
from paste import proxy  # Using to proxy requests to remote server

app = Flask(
    __name__, static_folder='app',
    static_url_path=''  # To serve static file as root dir.
)

# Create a proxy server to serve backend requests.
backend_app = proxy.make_proxy(
    None, 'http://example.com/', allowed_request_methods='POST'
)

app.wsgi_app = RequestMethodDispatcher(app.wsgi_app, {
    'POST': backend_app,
})

if __name__ == "__main__":
    app.run('0.0.0.0', 5000)
Go Top