Python
217 bites tagged Python — interview questions with model answers, and 60-second explainers.
FastAPI's WebSocket State Machine
FastAPI manages WebSockets with a state machine, tracking client and application states separately. You must explicitly `accept()` a connection before communicating. This is key for chat or notification features.
FastAPI Lifespan: Code Before Startup, After Shutdown
FastAPI's lifespan events are "open for business" and "closing time" routines that run once before startup and after shutdown. Use them to initialize a DB pool or load a model. The footgun is putting request-specific logic here; it runs once only.
FastAPI Behind a Reverse Proxy: Fixing Docs URLs
A reverse proxy can hide the full URL from your FastAPI app, breaking OpenAPI docs. Tell your app about the proxy's path prefix by setting the `root_path` during initialization to ensure all generated URLs are correct.
Customizing FastAPI's Swagger UI Behavior
Treat FastAPI's Swagger UI as a configurable frontend, not a static page. You can customize its behavior by passing a dictionary of settings on app startup. This is useful for changing themes or pre-filling auth fields. The footgun: keys must be camelCase.
Exclude a FastAPI Endpoint from OpenAPI Docs
Hide an endpoint from your API docs by setting `include_in_schema=False`. Use this for internal or deprecated endpoints. The footgun: this only hides the endpoint from documentation; it remains fully functional and accessible if the URL is known.
FastAPI: Documenting Additional API Responses
Document every possible API response, not just the happy path. The `responses` decorator parameter lets you define alternative status codes and schemas, like a 404 error model, making your OpenAPI docs complete.
FastAPI: Configure API Metadata for Better Docs
Think of FastAPI metadata as your project's business card. It sets the title, version, and description in your auto-generated docs, making your API professional and discoverable. The main footgun is forgetting to update the version string after a release.
Testing WebSockets in FastAPI
Test a WebSocket conversation by scripting both sides. FastAPI's TestClient provides a `websocket_connect` context manager to send messages and assert responses sequentially, which is crucial for testing chats or live data feeds.
Mocking with Pytest's monkeypatch
Pytest's `monkeypatch` is a temporary stunt double for your code, safely swapping out functions or environment variables for a single test. Use it to isolate tests from network calls or filesystem access.
Testing Async FastAPI with pytest-asyncio
To test async code, your tests must also be async. `pytest-asyncio` lets you write `async def test_...` functions to `await` operations like database checks after an API call.
Run One Test with Many Inputs using pytest.parametrize
Run one test function with many inputs using `@pytest.mark.parametrize`, avoiding repetitive code. It's ideal for checking a function against various inputs, edge cases, and expected failures. The footgun: mutable parameters like lists are passed by reference.
pytest Fixtures: Reusable Test Setups
Pytest fixtures are reusable functions for test setup, like creating sample data. Your tests request them by name as arguments, and pytest automatically runs them and injects the results.
FastAPI's TestClient: Test Your API Without a Live Server
FastAPI's TestClient simulates API requests in-memory, letting you test endpoints without a live server. Use it with pytest to verify status codes and responses. The main footgun is forgetting to `pip install httpx`, as it's a required dependency.
Celery: Offloading Work from Your FastAPI App
Celery lets your web app offload slow tasks to a separate process, keeping your API responsive. Use it for tasks that can't finish in a single HTTP request, like sending bulk emails or processing images.
Custom FastAPI Middleware: The BaseHTTPMiddleware Helper
FastAPI's BaseHTTPMiddleware lets you wrap endpoints to run code before and after they execute. Use it to add custom headers or log request times. The footgun: reading `request.body()` in the middleware will break the endpoint, as the body can only be read…
FastAPI Background Tasks: Don't Make the Client Wait
FastAPI background tasks let you run slow operations, like sending an email, *after* returning a response. This keeps your API fast. The main footgun: these are fire-and-forget; a server crash means the task is lost without a real message queue.
FastAPI RBAC: Using OAuth2 Scopes for Permissions
Treat OAuth2 scopes as a list of permissions. Instead of checking a user's role, you check if their token has the required scope (e.g., `items:write`) for an endpoint. FastAPI's Security dependency automates this check.
Password Hashing with Python's Passlib
Passlib turns plaintext passwords into secure, salted hashes that are safe to store. Use it in any Python app with user accounts to handle logins. The footgun: never compare hashes directly; always use the `.verify()` method to prevent timing attacks.
SQLAlchemy: Control When Your Relationships Load
SQLAlchemy's default lazy loading is convenient but can cause an N+1 query storm. Use eager loading (`joinedload`, `selectinload`) for collections you'll access to prevent many database round trips.
Beanie: Python Objects as MongoDB Documents
Beanie maps Pydantic models to MongoDB documents, letting you interact with the database using Python objects instead of raw queries. Use it in async apps like FastAPI for rapid, type-safe CRUD.
Motor: Don't Block Your Python App on MongoDB
Motor is the async bridge for Python apps to talk to MongoDB without blocking. Use it in FastAPI or other async frameworks to keep your server responsive during database queries.
Alembic: Version Control for Your Database Schema
Alembic is like Git for your database schema, providing versioned, reversible changes. Use it with SQLAlchemy to evolve your database structure alongside your code. The footgun is that autogeneration can miss changes; always review generated scripts.
SQLAlchemy 2.0: Async Without Blocking the Event Loop
SQLAlchemy 2.0 wraps its synchronous core with an async API, letting you `await` database calls without blocking your app's event loop. Use it in frameworks like FastAPI.
SQLAlchemy Declarative: Python Classes as Database Tables
SQLAlchemy's Declarative Mapping lets you define database tables as Python classes. You write a class with typed attributes, and SQLAlchemy generates the SQL. It's the standard way to use the ORM, turning database rows into Python objects.
Get Python bites daily.
Five a day, five minutes, offline. With quizzes so it sticks.
Open testing — you’ll join as an early tester.