🏡 Home | 📝 Writing | 💽 Work
Hosting a Python Server
2024-10-21
A recipe for running a Python-based web server available to the public internet.

Python App

import os

import uvicorn


def main() -> None:
    profile = os.environ.get("PROFILE", "dev")
    match profile:
        case "dev":
            # Used in local dev, so you can connect through your browser.
            uvicorn.run(
                "yarn_finder.wsgi:app",
                host="127.0.0.1",
                port=8080,
                reload=True,
            )

        case "prod":
            # Used in prod, for Nginx.
            uvicorn.run(
                "yarn_finder.wsgi:app",
                uds="/tmp/uvicorn.sock",
            )


if __name__ == "__main__":
    main()

You can find an up-to-date version in the GitHub repo for this project.

Getting a Server

Nginx

server {
	client_max_body_size 4G;

	server_name <your URL>;

	location / {
		proxy_set_header Host $http_host;
		proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
		proxy_set_header X-Forwarded-Proto $scheme;
		proxy_set_header Upgrade $http_upgrade;
		proxy_set_header Connection $connection_upgrade;
		proxy_redirect off;
		proxy_buffering off;
		proxy_pass http://uvicorn;
	}
}

map $http_upgrade $connection_upgrade {
	default upgrade;
	'' close;
}

# Note: this is where the uvicorn.sock thing comes back!
upstream uvicorn {
	server unix:/tmp/uvicorn.sock;
}

DNS Configuration

HTTPS Configuration

Running Your Code

Getting code to the cloud

Setting up uv

Get your server running