Running a Python ASGI app on Zeit Now v2

Now v2 really wants you to deploy static assets with serverless functions tucked away in a separate folder. They suggest creating modules like api/index.py which will be served up automatically as API backends to your client-side JavaScript.

It turns out you can subvert that model entirely and route all of your traffic through a single function - great for serving up Python WSGI or ASGI apps that handle traffic routing themselves.

the trick is to use the "routes" key in a now.json file like this:

{
    "version": 2,
    "builds": [
        {
            "src": "json_head.py",
            "use": "@now/python"
        }
    ],
    "routes": [
        {
            "src": "(.*)",
            "dest": "json_head.py"
        }
    ]
}

Here json_head.py is a Python module which uses Sanic to expose a app object that conforms to the ASGI protocol. The same trick works for Starlette too, and should work for libraries that expose WSGI protocol objects such as Flask.

Some examples I've built that use this pattern:

Here's the Zeit builder code that detects ASGI or WSGI apps, for a peek at how it works under the hood.

See also:

Created 2020-04-19T15:28:51-07:00, updated 2020-04-21T05:43:40-07:00 · History · Edit