All bites
The whole library, newest first. Filter by what you are here for, or pick a topic if you already know.
8664 bites
Page 8
Purpose of await next(request) in FastAPI middleware and timing effects
Tests ASGI middleware lifecycle. await next(request) forwards the request downstream to the endpoint and returns the response. Pre-call code touches the request; post-call code touches the response.
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.
Write a FastAPI middleware that adds X-Process-Time header
Tests FastAPI lifecycle and header mutation. Strong answers use the http middleware decorator, await call_next, compute elapsed time, and inject X-Process-Time before returning. Red flag: forgetting to await call_next or mutating headers after the return.
Which FastAPI CORSMiddleware parameters beyond allow_origins fix a PUT preflight?
Configure allow_methods for PUT and allow_headers for Authorization so the browser approves the cross-origin call.
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.
Propagating a correlation ID without parameter passing
Middleware reads or generates the header, stores it in a contextvars.ContextVar, service code reads it anywhere, and logging filters inject it.
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.
BackgroundTasks dependency vs response.background
The injected BackgroundTasks parameter lets endpoints and dependencies stack tasks and is the common path; response.background attaches a single Starlette task when you return a Response object…

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.
Why is FastAPI BackgroundTasks poor for multi-minute PDF generation?
Tests whether you know BackgroundTasks is same-process and for seconds, not minutes. Answer: propose a task queue with broker, workers, and result backend; return HTTP 202 with a job ID. Red flag: suggesting FastAPI workers instead of persistence and retries.
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.

Design DB transaction middleware and identify the background-task pitfall
Tests request-scoped DB lifecycle awareness. Strong answer: middleware closes the session on response, yet BackgroundTasks run afterward, so sharing that session causes crashes or leaks. Red flag: saying background tasks can reuse the request transaction.
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.
How do you test a FastAPI GET endpoint with pytest and TestClient?
Import TestClient and app, write a test_ function, call client.get("/items/1"), assert status_code == 200 and json() matches expected data.
What is FastAPI's TestClient and how does it differ from requests?
Tests if you know TestClient runs pytest against the app directly without a live server. Good answers note its HTTPX-based Requests-like API, passing the FastAPI app into the client, and simple asserts. Red flag: saying you need a running server and real URLs.

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.
Explain FastAPI dependency overrides with an in-memory SQLite test example
This tests FastAPI's hook for swapping dependencies cleanly in tests. A strong answer names app.dependency_overrides, defines a test-only in-memory SQLite session, and handles teardown. A red flag is patching globals or mocking ORM instead of dependency.
JWT: Signed JSON Claim Tokens
A JWT is a signed JSON envelope: it carries claim assertions in JSON, optionally encrypted, and proves who wrote it using either a private secret or a public/private key. Do not treat the payload as hidden unless encryption is actually enabled.
How do you test a FastAPI endpoint without real tokens?
Tests whether you know FastAPI's dependency override mechanism to isolate business logic from auth. A great answer describes using app.dependency_overrides to swap the auth Depends for a mock returning a fake user, then cleaning up after the test.

OAuth2 Password Flow: Trading Credentials for a Token
The OAuth2 Password Flow trades a user's credentials for a temporary access token. It's used in trusted first-party apps, like a mobile app logging into its own backend, to avoid sending a password with every API call.