Packaging and Deployment — Deploying to Railway
In this chapter you'll learn FastAPI production configuration and deploy the blog to Railway.
Production configuration management
(venv) $ pip install pydantic-settings python-dotenv
Example
File path: config.py
from
pydantic_settings
import
BaseSettings
class
Settings
(
BaseSettings
)
:
"""Application configuration (automatically read from the .env file)"""
app_name:
str
=
"RUNOOB Blog"
debug:
bool
=
False
secret_key:
str
=
"dev-secret-key-change-me"
database_url:
str
=
"sqlite:///./blog.db"
access_token_expire_minutes:
int
=
60
24
7
7 days
class
Config:
env_file
=
".env"
Specify the environment variable file
settings
=
Settings
(
)
creation .env File:
SECRET_KEY=a1b2c3d4...your-real-secret-key
DATABASE_URL=sqlite:///./blog.db
DEBUG=False
Generate the dependency file
(venv) $ pip freeze > requirements.txt
Ensure it includes the core dependencies: fastapi, uvicorn, sqlalchemy, jinja2, alembic, passlib, python-jose, python-multipart, sqladmin, pydantic-settings.
Configure the Procfile and start command
FastAPI uses an ASGI server, unlike Flask/Django's WSGI:
web: uvicorn main:app --host 0.0.0.0 --port $PORT
If you need multiple workers (recommended in production):
web: gunicorn -k uvicorn.workers.UvicornWorker -w 4 main:app
WSGI vs ASGI: Django/Flask use Gunicorn (a WSGI server), FastAPI uses Uvicorn (an ASGI server). Gunicorn itself is WSGI, but can use
uvicorn.workers.UvicornWorkerto run ASGI applications.
Push to GitHub
$ git init
$ echo "venv/" > .gitignore
$ echo "__pycache__/" >> .gitignore
$ echo "*.pyc" >> .gitignore
$ echo ".env" >> .gitignore
$ git add .
$ git commit -m "初始化 FastAPI 博客项目"
$ git branch -M main
$ git remote add origin https://github.com/你的用户名/fastapi-blog.git
$ git push -u origin main
Railway Deployment
- Access the railway.app, log in with GitHub
- New Project → Deploy from GitHub repo → Select fastapi-blog
- Railway automatically detects the Procfile
- Set environment variables in Variables
- Click Deploy
Environment variable configuration
| Variable Name | Value | Description |
|---|---|---|
| SECRET_KEY | A randomly generated long string | JWT signing secret |
| DATABASE_URL | injected by Railway | Production database |
After a successful deployment you'll get a link; visit /docs to see the Swagger docs and /admin to enter the admin panel.
Framework comparison
| Function | FastAPI | Django | Flask |
|---|---|---|---|
| ORM | SQLAlchemy | Django ORM (built-in) | Flask-SQLAlchemy |
| Data validation | Pydantic | Django Forms | Flask-WTF |
| Route organization | APIRouter | urls.py | Blueprint |
| User Authentication | JWT + OAuth2 | Session Auth (built-in) | Flask-Login(Session) |
| Database migrations | Alembic | makemigrations / migrate | Flask-Migrate |
| Admin site | sqladmin | Django Admin | Flask-Admin |
| API Documentation | /docs (automatic) | requires drf-spectacular | requires Flasgger |
| Server | Uvicorn(ASGI) | Gunicorn(WSGI) | Gunicorn(WSGI) |
Next Learning Directions
| Learning Direction | Who It's For | Recommended Starting Point |
|---|---|---|
| Async SQLAlchemy | When you need higher concurrency performance | Switch the synchronous Session to AsyncSession |
| FastAPI + Vue3/React front-end/back-end separation | SPA + API architecture | Replace Jinja2 templates with Vue3/React, and let FastAPI serve purely as an API backend |
| WebSocket | When you need real-time push (chat, notifications) | FastAPI natively supports WebSocket: @app.websocket() |
| PostgreSQL | Production-grade database | Replace DATABASE_URL and install asyncpg or psycopg2 |