# Deploy Python with Postgres

Run a FastAPI or Django app on Reverhost and connect it to the project's free Postgres 16 database.

## Create the database

```
npx ezhst db create main
npx ezhst db info --json
npx ezhst env set DATABASE_URL="postgresql://..."
```

The connection string uses a public host with TLS, so it also works from your laptop for migrations.

## FastAPI with SQLAlchemy

Add `fastapi`, `uvicorn`, `sqlalchemy` and `psycopg[binary]` to `requirements.txt`.

```db.py
import os

from sqlalchemy import create_engine, text

url = os.environ["DATABASE_URL"].replace("postgresql://", "postgresql+psycopg://", 1)
engine = create_engine(url, pool_size=5)


def count_users():
    with engine.connect() as conn:
        return conn.execute(text("select count(*) from users")).scalar()
```

The [Python template](/languages/python) runs FastAPI as is. See [FastAPI hosting](/free-fastapi-hosting) for the full Dockerfile.

## Django with dj-database-url

Add `dj-database-url` and `psycopg[binary]`, then read the URL in settings.

```mysite/settings.py
import os

import dj_database_url

DATABASES = {"default": dj_database_url.parse(os.environ["DATABASE_URL"], conn_max_age=60)}
```

[Django hosting](/free-django-hosting) has a Dockerfile that runs gunicorn and collects static files.

## Run migrations

Run them from your machine with `DATABASE_URL` set to the Reverhost connection string.

```
alembic upgrade head
python manage.py migrate
```

Use Alembic for SQLAlchemy and `manage.py migrate` for Django. Commit migration files so every environment applies the same changes.

## Deploy

```
npx ezhst build dockerfile template fastapi --apply
npx ezhst deploy
```

Each database allows 20 connections, so keep pools small. See the [Postgres product page](/products/postgres).

## Frequently asked questions

### Which Postgres driver should I use?

psycopg 3 for SQLAlchemy and Django, or asyncpg for async code. Both accept the connection string from `ezhst db info`.
