I need to initialize resources (database connection pool, Redis client, HTTP client) when my FastAPI app starts and clean them up when it shuts down. The old @app.on_event('startup') pattern is deprec...
python
CommonTrace リポジトリ内の python に関連するトレースが 119 件あります。
I want to use FastAPI's dependency injection system cleanly across route handlers. I have database sessions, current user extraction from JWT, and Redis clients that need to be injected. I want to use...
After handling an API request (e.g., creating a trace), I want to trigger background processing (generate embeddings, send a notification email) without blocking the response. I need this to run after...
I need to manage configuration for a FastAPI app across local dev, CI, and production environments. I use environment variables and .env files. I want type-safe settings with validation, defaults, and...
I need to bulk insert thousands of rows into PostgreSQL using SQLAlchemy 2.0 async. I want to do it efficiently with a single query (not one INSERT per row) and get back the generated IDs without a se...
I'm getting 'MissingGreenlet' or 'greenlet_spawn has not been called' errors when accessing related objects on my SQLAlchemy models in an async context. I need to understand which lazy loading strateg...
I need to version my FastAPI API (v1, v2 eventually) without breaking existing clients when I introduce breaking changes. I want to organize routes in separate router modules per version and apply ver...
I need structured JSON logging in my FastAPI application. I want request IDs correlated across log lines, log levels configurable via env var, and logs formatted as JSON in production but human-readab...
I need to run multiple async operations concurrently in Python and collect all their results. Some operations may fail and I want to handle errors per-task. I'm using Python 3.11+ and want to use the ...
I need to write async pytest tests for my FastAPI application. I need a test database that's rolled back after each test (not truncated), and I need to override FastAPI's database dependency so tests ...
I want to measure API request duration and expose it as a Prometheus metric. I need middleware that times every request, records the route, method, and status code, and exposes a /metrics endpoint for...
I need to implement a paginated list endpoint in FastAPI. The endpoint accepts optional filters (status, tag name) and pagination parameters (page, page_size). I want to avoid N+1 queries and get tota...
My API uses snake_case internally (Python convention) but the frontend expects camelCase JSON. I need Pydantic models that accept and output camelCase JSON while keeping snake_case attribute names in ...
I have a function that handles multiple edge cases and I want to test all of them without writing a separate test function per case. I want to use pytest's parametrize decorator to test with different...
I need to rate limit my FastAPI API endpoints. I want different limits for read vs write operations (e.g., 60 reads/min, 20 writes/min per API key). The rate limiter must be atomic to handle concurren...
I have a background worker (not FastAPI) that processes traces in a loop. Each batch of traces needs its own database session. I need to avoid session reuse across batches, handle connection pool exha...
My FastAPI application raises various exceptions in different layers (validation errors, database errors, business logic errors) and I want all errors to return the same JSON structure. I also want to...
I need to make HTTP calls to external APIs from my FastAPI application. I want a shared client with connection pooling (not a new client per request), configurable timeouts, and proper error handling....
I need to create an async context manager for managing resources that need cleanup (database connections, temp files, locks). I want to use it with both `async with` syntax and as a decorator.
I have a SQLAlchemy ORM model with sensitive fields (api_key_hash, internal_flags) that I don't want to expose in API responses. I also want to add computed fields to the response (e.g., is_verified c...
I need to enforce a composite unique constraint across multiple columns in SQLAlchemy (e.g., one vote per user per trace, unique domain reputation per user per tag). I also need a partial unique index...
I have a background worker that processes items concurrently, but I don't want to overwhelm the database or external API. I need to limit the number of concurrent coroutines processing at any time.
I need to add a new column to an existing PostgreSQL table that already has data. The column has a default value. I want to avoid locking the table and need to understand the migration ordering to han...
I need to push real-time updates to browser clients when traces are validated or new search results arrive. I want to use WebSockets with FastAPI, handle connection cleanup when clients disconnect, an...
I'm building a Python service and not sure whether to use Python dataclasses, Pydantic models, or attrs for different data structures. I need to understand the tradeoffs for API schemas, internal data...
My application makes calls to the OpenAI API and other external services. I want to write unit tests that don't make real HTTP calls, can test different response scenarios (success, error, timeout), a...
I'm writing Python code with strict type checking (mypy) and need to properly annotate functions that work with generic types: functions returning different types based on input, TypeVar with bounds, ...
My API has endpoints that return large datasets (100k+ rows). Offset-based pagination becomes slow at high page numbers. I need to implement cursor-based pagination that's efficient at any position in...
I need to insert records but update them if they already exist (upsert). This is common for incrementing counters, updating reputation scores, or syncing external data. I need the PostgreSQL-specific ...
I want to customize FastAPI's automatically generated OpenAPI documentation: add authentication scheme to Swagger UI, add custom descriptions and examples to request/response models, group endpoints b...
I need to stream large query results from PostgreSQL without loading everything into memory. I want to use a Python async generator that yields rows in batches, and I want to support both streaming HT...
My pytest test suite is growing and I'm having trouble managing shared fixtures. I need to organize conftest.py files across a test hierarchy, understand fixture scoping, and share fixtures between di...
I need a /health endpoint for Docker healthchecks and load balancer probes. The endpoint should verify the database connection and Redis connection are alive, return structured health status, and resp...
I need to automatically track when rows are inserted or updated in my database tables for audit purposes. I want to log changes without modifying every query in my codebase.
I'm using Python Enum classes for status fields and vote types in my application. I need them to work correctly with SQLAlchemy (stored as strings in PostgreSQL, not as database enum types), with Pyda...
I need an endpoint that accepts file uploads (CSV, JSON, images). I need to validate file type, size limit the upload, and process the file asynchronously without blocking the server. I want to handle...
I have multiple API instances behind a load balancer and need to broadcast events (trace validated, new search result) to all instances. Redis pub/sub will fan out messages to all subscribers. I need ...
My application has concurrent requests that update the same rows in different orders, causing deadlocks (ERROR: deadlock detected). I need to understand why deadlocks happen and how to prevent them in...
My Docker image for a FastAPI app is 2GB and takes 5 minutes to build. I need a multi-stage Dockerfile producing a slim production image, using layer caching effectively to avoid reinstalling packages...
I want to deploy my FastAPI application to fly.io with a managed PostgreSQL database. I need fly.toml configuration, migration execution before deployment, and secure secret management.
I have PostgreSQL with pgvector embeddings and a trust_score. I want semantic search that combines vector similarity with trust score for final ranking, without cutting off high-trust results before r...
I need to rank traces by user votes. Simple upvote/total ratio fails for low-vote items (1/1 = 100% looks better than 95/100 = 95%). I need Wilson score lower bound for confidence-interval-aware ranki...
I have multiple API instances behind a load balancer and need to broadcast events (trace validated, vote cast) to all instances simultaneously. Redis pub/sub fans out to all subscribers.
I need to retry failing async operations (external API calls, database operations under transient load) with exponential backoff. I want a reusable decorator and to retry only on specific exception ty...
I need to add a new NOT NULL column to an existing PostgreSQL table that has data. I need to avoid table locking in production and understand the correct staging for nullable -> backfill -> NOT NULL.
I need fast async pytest tests for my FastAPI application using a real database. I want tests to roll back after each test rather than truncating tables, and override the FastAPI database dependency w...
I want to stream OpenAI chat completion responses to users so tokens appear in real-time. I need to handle streaming in the backend (FastAPI) and forward it to the frontend using Server-Sent Events.
I need to integrate Stripe Checkout for subscription payments. Users click a button, get redirected to Stripe's hosted checkout page, complete payment, and return to my app.
I am migrating from Pydantic v1 to v2 and need custom validation: field-level validators that transform input (normalize strings, coerce types), cross-field validators comparing multiple fields, and c...
I want to measure API request duration and expose Prometheus metrics. I need middleware that times every request, records route and status code, and serves a /metrics endpoint for scraping.
I need a paginated list endpoint in FastAPI with optional filters (status, tag). I want efficient pagination with total count and no N+1 queries.
My FastAPI application raises various exceptions in different layers and I want all errors to return a consistent JSON structure. I also want to map internal exceptions to appropriate HTTP status code...
My API returns large datasets and offset-based pagination becomes slow at high page numbers. I need cursor-based pagination that stays O(log n) at any position in the dataset.
I need to decide when to use Python dataclasses, Pydantic models, TypedDict, or NamedTuple for different data structures in my application. Each has tradeoffs in validation, serialization, and overhea...
I need to bulk insert thousands of rows into PostgreSQL efficiently. Individual inserts in a loop are too slow. I want a single bulk INSERT and need the generated IDs back without a second SELECT.
I need to run multiple async operations concurrently and collect all results. I want to handle cases where some may fail independently and need Python 3.11+ structured concurrency approach.
I have a function handling many edge cases and want to test all of them without a separate test function per case. I want pytest parametrize with multiple inputs and expected outputs including error c...
I need to version my FastAPI API (v1, v2 eventually) without breaking existing clients. I want routes organized in separate modules per version with versioned URL prefixes and shared authentication.
I keep getting MissingGreenlet errors or N+1 queries when accessing related objects on SQLAlchemy models in an async context. I need to understand which loading strategies work with async and how to e...
I need to push real-time updates (trace validated, vote cast) to browser clients. I want WebSockets with FastAPI, clean handling of client disconnections, and broadcast to all connected clients.
I need to automatically track when rows are inserted or updated in PostgreSQL for audit purposes. I want this without modifying every query in my codebase.
After handling an API request (creating a trace), I want to trigger background processing (generate embeddings) without blocking the response. The work should run after the response is sent to the cli...
I need to manage configuration for a FastAPI app across local dev, CI, and production environments using environment variables and .env files. I want type-safe settings with validation and defaults.
I have a SQLAlchemy ORM model with sensitive fields I don't want in API responses (api_key_hash, internal flags). I also want computed fields in the response. I need Pydantic v2 ORM mode.
I am using Python Enum classes for status fields in my application and need them to work with SQLAlchemy (stored as strings), with Pydantic validation, and with JSON serialization without a custom enc...
I need to unit test code that depends on external services (OpenAI, database, Redis). I want to mock these dependencies to test my business logic in isolation without real I/O.
I have expensive database queries for search results I want to cache in Redis. I need a clean cache-aside pattern that serializes Pydantic models, handles Redis unavailability gracefully, and avoids s...
I am hitting OpenAI rate limits and getting RateLimitError exceptions. I need robust retry logic with exponential backoff specifically for OpenAI API calls, and I need to handle different error types ...
I need to handle webhooks from multiple providers (Stripe, GitHub, custom services). I need a reusable pattern for signature verification, idempotent processing, and handling duplicate deliveries.
My tests need realistic data (traces with tags, users with votes). Creating data manually in each test is verbose and fragile. I want factory fixtures that generate realistic test data with sensible d...
I want to go beyond example-based tests to automatically discover edge cases in my code. I need property-based testing that generates diverse inputs and finds cases I would not think of manually.
I need consistent structured logging across my Python application. Logs need to be machine-parseable JSON in production but human-readable in development, with context (request_id, user_id) propagated...
I need API key authentication for my FastAPI service. API keys must be stored securely (not plaintext), validated on every request, and I want to support multiple keys per user with revocation.
I need to stream large data exports from my FastAPI application. I want to generate NDJSON (newline-delimited JSON) as an async generator and stream it to the client without loading all data into memo...
I have multiple API instances and need to ensure only one runs a specific operation at a time (e.g., leaderboard rebuild, scheduled job). I need a distributed mutex without adding a separate locking s...
Alembic's autogenerate misses some schema changes: custom PostgreSQL types, check constraints, and index changes. I need to configure autogenerate to detect more changes and add manual DDL for unsuppo...
I have multiple FastAPI instances behind a load balancer. Simple in-memory rate limiting does not work because requests are distributed across instances. I need Redis-based rate limiting that works ac...
I want to let users log in with their GitHub account. I need to handle the OAuth2 flow: redirect to GitHub, receive the callback code, exchange for user info, and create/update a user in my database.
I want to measure test coverage in my Python project, enforce minimum coverage thresholds in CI, and track coverage changes over time. I use pytest and want coverage reported in the CI run.
I have Python code using os.path and string concatenation for file paths that breaks on Windows. I need to use pathlib for cross-platform file operations that work on Linux, macOS, and Windows.
I need to build a command-line interface for my application with subcommands (import, export, stats), options with validation, and help text. I want it to be testable and support both interactive and ...
I am using Python dataclasses for internal data objects. I need mutable default values (lists, dicts), computed fields that derive from other fields, and validation in __post_init__.
I have a many-to-many relationship between traces and tags. I need to create the join table correctly in SQLAlchemy, handle tag insertion with get-or-create semantics, and query traces by tag efficien...
I need my FastAPI routes to participate in database transactions where multiple operations must succeed or fail together. I want a dependency that manages the transaction lifecycle.
Python Docker images are large (1GB+) because they include build tools, pip cache, and development packages. Need a lean production image while keeping a full dev environment. Using uv for fast depend...
Need to send transactional emails (welcome emails, password resets, notifications) from a FastAPI application. Evaluating Resend as a simpler alternative to SendGrid/Mailgun with a clean Python SDK.
Writing tests for a function that should behave differently based on many input combinations. Duplicating test functions for each case leads to hundreds of lines of copy-pasted code. Need a clean way ...
Tests call external APIs (OpenAI, Stripe, GitHub). Real API calls make tests slow, expensive, and flaky. Need to intercept HTTP calls at the transport layer so the application code doesn't need to cha...
Using Pydantic BaseModel for everything including internal data transfer objects (DTOs) that never touch the API boundary. Pydantic validation overhead is unnecessary for internal models. Need guidanc...
Executing multiple independent async operations sequentially instead of concurrently. Using `asyncio.gather()` but need better error handling when one task fails — gather continues other tasks even on...
SQLAlchemy ORM queries are unexpectedly slow. EXPLAIN ANALYZE shows hundreds of small queries instead of a few efficient ones. The N+1 problem: loading a list of traces then accessing trace.tags trigg...
Expensive computations (tag normalization regex compilation, settings lookups, configuration parsing) run repeatedly with the same inputs. Need simple memoization without external caching infrastructu...
FastAPI services are tightly coupled to concrete implementations (PostgreSQL, Redis, specific email provider). Want to swap implementations for testing without monkey-patching or complex mocking setup...
Building code that needs to work with both asyncio and Trio event loops (or library code that shouldn't dictate the event loop). Also need nursery-style task cancellation that TaskGroup provides but w...
Application raises various exceptions (ValidationError, NotFound, PermissionDenied) but they all return inconsistent error responses. Clients can't reliably parse error details. Need a consistent erro...
Getting errors like 'There is no current event loop' or 'coroutine was never awaited' in async Python code. Also confusion about when to use asyncio.run() vs await, and how to call async code from syn...
Pydantic models need computed/derived fields that are calculated from other fields (e.g., full_name from first/last, formatted dates, masked API keys). Also need custom serialization (snake_case to ca...
Using OpenAI chat completions to extract structured data from user input (classify intent, extract entities, fill forms). Parsing JSON from unstructured LLM output is fragile and requires complex prom...
Multiple workers process tasks concurrently and need to ensure only one worker handles a given resource at a time. Need a distributed lock that works across multiple API instances with automatic expir...
Inserting thousands of rows one at a time with individual session.add() calls is too slow. Need bulk inserts that return the auto-generated IDs of inserted rows for downstream processing.
Deploying a FastAPI application to Fly.io. Need to configure machine sizes, auto-scaling, health checks, persistent volumes for file storage, and secrets management for the deployment.
Calling the GitHub REST API to fetch repository data, user information, and pull request details. Hitting rate limits (60 req/hour unauthenticated, 5000/hour with token). Need to handle pagination and...
Need to store and serve user-uploaded files (images, PDFs). Storing files in the filesystem doesn't work with multiple API instances or ephemeral containers. Need object storage that works with AWS S3...
Working with union types and need TypeScript-style type guards in Python. After checking `isinstance(x, str)`, the type checker should know `x` is a `str` in that branch. Also need custom narrowing fu...
Test fixtures are duplicated across multiple test files. Each file has its own database setup, mock clients, and test data factories. Need a way to share fixtures across an entire test suite without i...
Resources like database connections, file handles, locks, and HTTP clients need cleanup even when exceptions occur. Using try/finally everywhere is verbose. Need the context manager pattern for both c...
Need real-time bidirectional communication between browser clients and the FastAPI server. REST/SSE only support server-to-client. Building a live collaboration feature where multiple users see update...
Using string literals for status values ('pending', 'validated', 'active') spread across the codebase. Typos cause silent bugs, IDEs can't autocomplete, and it's hard to find all places a status value...
Using Python's standard logging module but log output is unstructured text that's hard to search in log aggregation tools (Datadog, Grafana Loki, CloudWatch). Need structured JSON logs with consistent...
Application needs configuration from multiple sources: environment variables override .env file, which overrides defaults. Also need nested settings objects (database config, Redis config) and type co...
Background tasks are blocking the API event loop — image processing, email sending, report generation take seconds. FastAPI BackgroundTasks run in the same event loop. Need a proper job queue that run...
Multiple service implementations (email: Resend, SendGrid; storage: S3, R2, local) need to be swappable. Using duck typing alone makes it unclear what methods a service must implement. Need formal int...
FastAPI application with SQLAlchemy has database connection issues under load: timeouts, 'too many connections' PostgreSQL errors, and connection leaks. Default connection pool settings are not tuned ...
Calling external APIs (OpenAI, Stripe, GitHub) that occasionally return 429 (rate limit) or 503 (transient errors). Need automatic retry with exponential backoff, jitter to avoid thundering herd, and ...
Alembic migration needs to modify an existing column (change type, add constraint) in a way that works on both PostgreSQL (production) and SQLite (tests/development). PostgreSQL supports ALTER COLUMN ...
Need to run Alembic migrations that work on both PostgreSQL and SQLite. SQLite doesn't support ALTER TABLE for column renames or type changes, causing migration failures in test environments.
Need to implement rate limiting for an API. Token bucket is too bursty, and fixed window has the boundary problem where a user can double their limit across two windows.
CI pipeline uses matrix builds for multiple Python versions but stops all jobs when one fails. Need all matrix combinations to complete so developers see the full picture of compatibility.
MCP server (FastMCP 3.0.0) deployed to Railway crashes at runtime with `ModuleNotFoundError: No module named 'httpx'`, even though `httpx>=0.27` is listed under `[project].dependencies` in pyproject.t...