Python Backend — Production Skill
FastAPI (Preferred for APIs)
Project Structure
src/
├── app/
│ ├── main.py # FastAPI app factory
│ ├── config.py # Settings (pydantic-settings)
│ ├── dependencies.py # Shared FastAPI deps (auth, db)
│ ├── routers/
│ │ ├── users.py
│ │ └── products.py
│ ├── models/ # SQLAlchemy ORM models
│ │ └── user.py
│ ├── schemas/ # Pydantic request/response schemas
│ │ └── user.py
│ ├── crud/ # DB operations (thin layer over SQLAlchemy)
│ │ └── user.py
│ ├── services/ # Business logic
│ │ └── email.py
│ └── core/
│ ├── security.py # JWT, hashing
│ └── database.py # SQLAlchemy session
├── tests/
├── alembic/ # DB migrations
├── pyproject.toml
└── Dockerfile
App Factory
from contextlib import asynccontextmanager
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.middleware.trustedhost import TrustedHostMiddleware
from app.routers import users, products, auth
from app.core.database import engine
from app.config import settings
@asynccontextmanager
async def lifespan(app: FastAPI):
yield
def create_app() -> FastAPI:
app = FastAPI(
title=settings.PROJECT_NAME,
version=settings.VERSION,
docs_url="/docs" if settings.DEBUG else None,
redoc_url=None,
lifespan=lifespan,
)
app.add_middleware(
CORSMiddleware,
allow_origins=settings.CORS_ORIGINS,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
app.add_middleware(TrustedHostMiddleware, allowed_hosts=settings.ALLOWED_HOSTS)
app.include_router(auth.router, prefix="/api/v1/auth", tags=["auth"])
app.include_router(users.router, prefix="/api/v1/users", tags=["users"])
return app
app = create_app()
Settings (pydantic-settings)
from pydantic_settings import BaseSettings, SettingsConfigDict
from pydantic import PostgresDsn, computed_field
class Settings(BaseSettings):
model_config = SettingsConfigDict(env_file=".env", case_sensitive=False)
PROJECT_NAME: str = "MyAPI"
VERSION: str = "1.0.0"
DEBUG: bool = False
DATABASE_URL: PostgresDsn
SECRET_KEY: str
ACCESS_TOKEN_EXPIRE_MINUTES: int = 30
REFRESH_TOKEN_EXPIRE_DAYS: int = 7
CORS_ORIGINS: list[str] = []
ALLOWED_HOSTS: list[str] = ["*"]
REDIS_URL: str = "redis://localhost:6379"
settings = Settings()
Database (SQLAlchemy 2.0 async)
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine, async_sessionmaker
from sqlalchemy.orm import DeclarativeBase
from app.config import settings
engine = create_async_engine(
str(settings.DATABASE_URL).replace("postgresql://", "postgresql+asyncpg://"),
pool_size=20,
max_overflow=0,
echo=settings.DEBUG,
)
AsyncSessionLocal = async_sessionmaker(engine, expire_on_commit=False)
class Base(DeclarativeBase):
pass
async def get_db() -> AsyncSession:
async with AsyncSessionLocal() as session:
try:
yield session
await session.commit()
except Exception:
await session.rollback()
raise
Models
from datetime import datetime
from sqlalchemy import String, Boolean, DateTime, func
from sqlalchemy.orm import Mapped, mapped_column
from app.core.database import Base
class User(Base):
__tablename__ = "users"
id: Mapped[int] = mapped_column(primary_key=True, index=True)
email: Mapped[str] = mapped_column(String(255), unique=True, index=True, nullable=False)
hashed_password: Mapped[str] = mapped_column(String(255), nullable=False)
full_name: Mapped[str | None] = mapped_column(String(255))
is_active: Mapped[bool] = mapped_column(Boolean, default=True)
is_superuser: Mapped[bool] = mapped_column(Boolean, default=False)
created_at: Mapped[datetime] = mapped_column(DateTime, server_default=func.now())
updated_at: Mapped[datetime] = mapped_column(DateTime, server_default=func.now(), onupdate=func.now())
Schemas (Pydantic v2)
from pydantic import BaseModel, EmailStr, Field, ConfigDict
from datetime import datetime
class UserBase(BaseModel):
email: EmailStr
full_name: str | None = None
class UserCreate(UserBase):
password: str = Field(min_length=8, max_length=100)
class UserUpdate(BaseModel):
full_name: str | None = Field(None, max_length=255)
password: str | None = Field(None, min_length=8)
class UserResponse(UserBase):
model_config = ConfigDict(from_attributes=True)
id: int
is_active: bool
created_at: datetime
Router
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.database import get_db
from app.schemas.user import UserCreate, UserResponse, UserUpdate
from app.crud import user as crud_user
from app.dependencies import get_current_user
from app.models.user import User
router = APIRouter()
@router.get("/me", response_model=UserResponse)
async def get_current_user_info(current_user: User = Depends(get_current_user)):
return current_user
@router.post("/", response_model=UserResponse, status_code=status.HTTP_201_CREATED)
async def create_user(user_in: UserCreate, db: AsyncSession = Depends(get_db)):
existing = await crud_user.get_by_email(db, email=user_in.email)
if existing:
raise HTTPException(status_code=400, detail="Email already registered")
return await crud_user.create(db, obj_in=user_in)
@router.patch("/me", response_model=UserResponse)
async def update_user(
user_in: UserUpdate,
current_user: User = Depends(get_current_user),
db: AsyncSession = Depends(get_db),
):
return await crud_user.update(db, db_obj=current_user, obj_in=user_in)
Authentication (JWT)
from datetime import datetime, timedelta, timezone
from passlib.context import CryptContext
from jose import JWTError, jwt
from app.config import settings
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
def hash_password(password: str) -> str:
return pwd_context.hash(password)
def verify_password(plain_password: str, hashed_password: str) -> bool:
return pwd_context.verify(plain_password, hashed_password)
def create_access_token(subject: str | int) -> str:
expire = datetime.now(timezone.utc) + timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)
return jwt.encode({"sub": str(subject), "exp": expire}, settings.SECRET_KEY, algorithm="HS256")
def decode_token(token: str) -> str:
payload = jwt.decode(token, settings.SECRET_KEY, algorithms=["HS256"])
return payload["sub"]
from fastapi import Depends, HTTPException, status
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
bearer = HTTPBearer()
async def get_current_user(
credentials: HTTPAuthorizationCredentials = Depends(bearer),
db: AsyncSession = Depends(get_db),
) -> User:
try:
user_id = decode_token(credentials.credentials)
except JWTError:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token")
user = await crud_user.get(db, id=int(user_id))
if not user or not user.is_active:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Inactive user")
return user
Background Tasks (Celery + Redis)
from celery import Celery
from app.config import settings
celery_app = Celery("worker", broker=settings.REDIS_URL, backend=settings.REDIS_URL)
celery_app.conf.task_serializer = "json"
celery_app.conf.result_expires = 3600
@celery_app.task(bind=True, max_retries=3)
def send_welcome_email(self, user_id: int):
try:
pass
except Exception as exc:
raise self.retry(exc=exc, countdown=60)
from app.worker import send_welcome_email
send_welcome_email.delay(user.id)
Error Handling
from fastapi import Request
from fastapi.responses import JSONResponse
from fastapi.exceptions import RequestValidationError
async def validation_exception_handler(request: Request, exc: RequestValidationError):
return JSONResponse(
status_code=422,
content={"detail": exc.errors(), "body": exc.body},
)
app.add_exception_handler(RequestValidationError, validation_exception_handler)
Testing
import pytest
import pytest_asyncio
from httpx import AsyncClient, ASGITransport
from sqlalchemy.ext.asyncio import create_async_engine, async_sessionmaker
from app.main import app
from app.core.database import get_db, Base
TEST_DB_URL = "postgresql+asyncpg://test:test@localhost:5432/test_db"
@pytest_asyncio.fixture
async def db():
engine = create_async_engine(TEST_DB_URL)
async with engine.begin() as conn:
await conn.run_sync(Base.metadata.create_all)
session = async_sessionmaker(engine, expire_on_commit=False)
async with session() as s:
yield s
async with engine.begin() as conn:
await conn.run_sync(Base.metadata.drop_all)
@pytest_asyncio.fixture
async def client(db):
app.dependency_overrides[get_db] = lambda: db
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as ac:
yield ac
app.dependency_overrides.clear()
async def test_create_user(client):
response = await client.post("/api/v1/users/", json={"email": "[email protected]", "password": "secret123"})
assert response.status_code == 201
assert response.json()["email"] == "[email protected]"
pyproject.toml
[tool.poetry]
name = "myapi"
version = "0.1.0"
python = "^3.12"
[tool.poetry.dependencies]
fastapi = "^0.115"
uvicorn = {extras = ["standard"], version = "^0.32"}
sqlalchemy = "^2.0"
asyncpg = "^0.30"
pydantic-settings = "^2.6"
python-jose = {extras = ["cryptography"], version = "^3.3"}
passlib = {extras = ["bcrypt"], version = "^1.7"}
alembic = "^1.14"
httpx = "^0.28"
celery = {extras = ["redis"], version = "^5.4"}
[tool.poetry.dev-dependencies]
pytest = "^8"
pytest-asyncio = "^0.24"
pytest-cov = "^6"
ruff = "^0.8"
mypy = "^1.13"
[tool.ruff.lint]
select = ["E", "F", "I", "N", "UP", "S", "B"]
[tool.mypy]
strict = true
Alembic Migrations
alembic init alembic
alembic revision --autogenerate -m "add users table"
alembic upgrade head
alembic downgrade -1
Django (Alternative for Full-Stack/Admin)
DATABASES = {
"default": {
"ENGINE": "django.db.backends.postgresql",
"NAME": env("DB_NAME"),
"USER": env("DB_USER"),
"PASSWORD": env("DB_PASSWORD"),
"HOST": env("DB_HOST"),
"CONN_MAX_AGE": 60,
}
}
CACHES = {
"default": {
"BACKEND": "django_redis.cache.RedisCache",
"LOCATION": env("REDIS_URL"),
}
}
from rest_framework import serializers, viewsets, permissions
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ["id", "email", "full_name", "created_at"]
read_only_fields = ["id", "created_at"]
class UserViewSet(viewsets.ModelViewSet):
serializer_class = UserSerializer
permission_classes = [permissions.IsAuthenticated]
def get_queryset(self):
return User.objects.filter(is_active=True)
Production Checklist