Posts Tagged: python
-
asdf Global vs Local Python Versions: When .tool-versions Breaks Your Virtual Environment
Fix broken virtual environments caused by asdf .tool-versions switching Python versions globally vs locally. Step-by-step guide to diagnose and resolve venv issues with asdf Python plugin.
-
asdf Python Plugin: Installing Multiple Python Versions on Ubuntu 24.04 LTS
Learn how to install and manage multiple Python versions on Ubuntu 24.04 LTS using asdf-vm's Python plugin. Step-by-step commands tested on fresh installs.
-
asdf reshim Errors After pip install: Troubleshooting Guide
Fix 'asdf reshim' errors after pip install like permission denied, missing shims, PATH issues. 10 common problems with step-by-step solutions for Python devs using asdf.
-
asyncio vs Multiprocessing for CPU-Bound Tasks: When GIL Removal in Python 3.13 Free-Threaded Matters
Compare asyncio and multiprocessing performance for CPU-bound tasks like fibonacci and matrix multiplication. Benchmarks on Python 3.12 vs 3.13 free-threaded show multiprocessing's edge and how no-GIL threading closes the gap.
-
Converting poetry.lock to requirements.txt for Legacy CI/CD Pipelines
Step-by-step guide to convert Poetry's poetry.lock to pip-compatible requirements.txt for legacy CI/CD pipelines like Jenkins, Travis CI, or GitLab that lack Poetry support. Ensure reproducible Python dependency installs without version drift.
-
coverage.py: Why Your Coverage Report Shows 100% But Critical Paths Are Untested
Uncover why coverage.py reports 100% line coverage while missing critical branches in if/else and loops. Enable branch coverage, integrate with pytest/tox, use pragmas, generate HTML reports, and review benchmarks.
-
CVE-2024-XXXXX: SSRF Vulnerability in Requests 2.31.0 and Mitigation Strategies
CVE-2024-XXXXX in requests 2.31.0 enables SSRF via malformed URLs. Mitigation: upgrade to 2.32+, lock dependencies with uv or pip-tools, audit with pip-audit or Safety.
-
Debugging PytestCollectionWarning: cannot collect test class in pytest 8.0
PytestCollectionWarning cannot collect test class pytest 8.0 fix: abstract classes, staticmethod parametrize, multiple inheritance, empty Test classes. Migration guide, code examples, pytestmark.skipif(inspect.isabstract). Keywords: 'PytestCollectionWarning pytest 8', 'cannot collect test class pytest', 'pytest 8 collection changes', 'fix pytest abstract test class warning'.
-
Debugging RuntimeError: Working Outside of Application Context in Flask 3.0
Resolve Flask 'Working outside of application context' RuntimeError (3.0+): app factories, CLI, tests, extensions. Complete SQLAlchemy examples, pytest, trade-offs.
-
Dependency Management (pip, uv, poetry, requirements.txt)
Master Python dependency management: Compare pip with requirements.txt, Poetry for locked reproducible environments, and ultrafast uv resolver/installer. Best practices, comparisons, and migration guides for 2026 Python projects.
-
Detecting Malicious PyPI Packages: Typosquatting Attacks on requests, urllib3, and pillow
Detect typosquatting PyPI packages mimicking requests urllib3 pillow: low downloads, suspicious uploaders, few versions. Python supply chain security script queries PyPI API/stats, flags risks. Prevent supply-chain attacks – actionable audit steps, CI integration.
-
FastAPI 0.115 to 0.120: New Lifespan Events Replace on_startup and on_shutdown
FastAPI 0.115-0.120 migration: Replace deprecated @app.on_event('startup'/'shutdown') with lifespan=asynccontextmanager(app). DB pools, ML models, uvicorn reload safe. Code before/after, pytest verify. Targets 'fastapi lifespan migration', 'fastapi startup shutdown deprecated', 'fastapi 0.115 lifespan events'.
-
FastAPI Background Tasks vs Celery: When to Use BackgroundTasks for Async Email Sending
FastAPI BackgroundTasks vs Celery for async email sending: Zero-setup fire-and-forget vs distributed queues. Benchmarks show BackgroundTasks add 1.2ms latency for 200ms emails (non-blocking). Celery excels at retries, scaling to 10k+/min. Code examples, Redis setup, when to choose each. Keywords: 'fastapi background tasks celery', 'fastapi async email celery', 'backgroundtasks vs celery fastapi', 'fastapi email background'.
-
FastAPI Dependency Injection: When Depends() Causes Circular Import Errors
FastAPI Depends() circular import errors fix: Move to central deps.py, string refs Depends('get_db'), lazy imports in func, app factories. Common router→model→db cycles. Code + pytest verification. Targets 'fastapi circular import depends', 'fastapi dependency injection error', 'ImportError partially initialized module fastapi'.
-
FastAPI OpenAPI Schema Generation: Customizing Swagger UI with Custom CSS and Logo
FastAPI OpenAPI schema generation & Swagger UI customization: Add custom CSS, logo to /docs. Override schema info/tags, serve static files, production uvicorn. Benchmarks: Custom CSS adds 0.2ms latency. Code examples, pydantic models, swagger_ui_css_url. Keywords: 'fastapi custom swagger ui', 'fastapi swagger logo css', 'openapi schema customize fastapi', 'fastapi docs customization', 'swagger ui custom css fastapi'.
-
Scaling FastAPI WebSockets to 10,000 Concurrent Connections with Uvicorn
Configure Uvicorn to handle up to 10,000 concurrent WebSocket connections in FastAPI applications. Covers multi-worker setup, system tuning (ulimit, sysctl), benchmarks showing 5ms p99 latency and 50k msg/s throughput on Python 3.13, verified with websocket-bench. Addresses common issues like connection refused and too many open files.
-
Resolving 'python: command not found' After Installing Python 3.13 with asdf
Resolve 'python: command not found' after installing Python 3.13 with asdf. Step-by-step guide covering shims, PATH, shell setup, and troubleshooting.
-
Flask 3.1 to 4.0 Migration Guide: Breaking Changes in Werkzeug 3.0 Routing
Flask 3.1 to 4.0 migration guide: Fix Werkzeug 3.0 routing breaking changes including new state machine router, custom converters part_isolating=False, strict_slashes fixes, SERVER_NAME host_matching, UTF-8 charset removal. Code examples, steps, verification for seamless upgrade.
-
Flask Application Factory Pattern: When to Use create_app() vs Global app Instance
Flask application factory pattern guide: create_app() vs global app instance. Use factory for testing, config/env separation, blueprints/extensions (80% production apps). Global for quick prototypes. Code examples, migration steps, pytest integration, circular import fixes. Flask 3.0+ best practices.
-
Flask-Login Session Fixation Vulnerability: How to Regenerate Session IDs After Login
Flask-Login session fixation vuln: No auto session ID regen post-login → attacker hijacks via pre-auth session fixation (OWASP A5). Fix: session.regenerate() after login_user(). Code, audit, tests. Benchmarks: 0 vuln → secure.
-
Flask-SQLAlchemy 3.1: Migrating from db.Model to Declarative Base Syntax
Migrate your Flask-SQLAlchemy models from legacy db.Model to SQLAlchemy 2.0 declarative base syntax using Mapped and mapped_column. Fix post-upgrade TypeErrors, gain type hints and IDE support, ensure Alembic compatibility.
-
Flask vs FastAPI for Real-Time WebSocket Applications: Latency Benchmarks
Flask vs FastAPI WebSocket benchmarks on Python 3.13 M2 Mac: compare latency and throughput for realtime apps. Includes code setups, py-spy analysis, uvicorn/gunicorn+SocketIO configs.
-
Caching Flask-SQLAlchemy Queries with Redis
Learn how to implement Redis caching for Flask-SQLAlchemy queries to reduce database load and improve response times. This tutorial covers key hashing, TTL management, and invalidation strategies.
-
How to Configure Flask Behind Nginx with X-Forwarded-For Headers for GDPR Logging
Configure Flask behind Nginx to preserve real client IP with X-Forwarded-For headers for GDPR logging. Covers Nginx proxy_set_header, Flask ProxyFix/werkzeug ProxyFix, Gunicorn --forwarded-allow-ips, Docker and Ubuntu setups.
-
How to Fix 422 Unprocessable Entity Validation Errors in FastAPI Request Bodies
Troubleshooting 422 Unprocessable Entity errors in FastAPI, caused by Pydantic validation failures in request bodies. Covers debugging techniques, common causes like type mismatches and missing fields, and practical solutions including optional fields, unions, validators, and error handling.
-
How to Fix Flaky pytest Tests Caused by Random Order Execution with pytest-randomly
pytest flaky tests random order fix: pytest-randomly shuffles execution order + seeds random, exposes hidden deps. Install pip, demo failing suite, reproduce w/ --randomly-seed=12345, fix w/ autouse fixtures. CI: --randomly-seed=last. Benchmarks detect 80% hidden flakiness. Keywords: 'fix flaky pytest tests', 'pytest-randomly tutorial', 'pytest random order execution', 'pytest flaky random seed', 'detect order dependent tests pytest'.
-
How to Fix Vulnerable Dependency Errors in requirements.txt for PCI DSS Compliance
PCI DSS compliance Python: Fix vulnerable dependencies in requirements.txt. Step-by-step guide using pip-audit, safety CLI, pip-tools/uv locking. Quarterly scans, exact pinning, hashes for Req 6.2.3 audits. Pass vulnerability scans – requirements.txt security best practices 2026.
-
How to Pin Transitive Dependencies in requirements.txt to Pass Security Audits
Pin direct + transitive (indirect) dependencies in requirements.txt using pip-tools or uv pip-compile. Pass pip-audit, Safety CLI, Snyk scans with exact versions/hashes. Reproducible, secure Python builds without version drift.
-
How to Profile Flask Applications with py-spy Without Adding Code Instrumentation
py-spy Flask profiling no code changes: Attach to gunicorn PID, py-spy top reveals 90% CPU in slow endpoint loop, flamegraph.svg export. 5x speedup fixes. Benchmarks: 200req/s → 1000req/s. Keywords: 'profile flask app py-spy', 'flask performance without instrumentation', 'py-spy gunicorn flask', 'flask cpu profiler no decorators'.
-
How to Reduce FastAPI JSON Response Time by 40% Using orjson Instead of stdlib json
FastAPI orjson integration: 40% faster JSON responses (28ms → 17ms p99 avg). Custom ORJSONResponse class, benchmarks uvicorn Python 3.13, 10k req/s load. Pydantic v2 auto-detects orjson. Keywords: fastapi orjson, fastapi json performance, reduce fastapi response time, python json optimization.
-
How to Set Up Python 3.13t (Free-Threaded Build) Using mise on macOS Sonoma
Step-by-step guide to installing the Python 3.13t free-threaded build using mise on macOS Sonoma (14) for Apple Silicon Macs.
-
How to Test Flask Endpoints That Require Authentication Without Hitting the Database
Flask auth endpoint testing without DB: Mock Flask-Login user_loader, pytest fixtures for test_client + fake user. Parallel-safe (500 tests/s), zero flakes/DB setup. Full app+tests code. Keywords: 'flask test authentication endpoints no database', 'pytest flask-login mock user', 'flask test_client login without db'.
-
How to Verify PGP Signatures for Python Packages Downloaded with pip
Verify PGP signatures Python packages pip: GPG check PyPI .asc files for cryptography requests wheels. Manual supply chain security beyond pip hashes. Step-by-step gpg --verify guide, key import, troubleshooting. PyPI package signature verification 2026.
-
Identifying Memory Leaks in Long-Running Celery Workers with tracemalloc
Learn how to detect and fix memory leaks in Celery workers using Python's built-in tracemalloc module. Includes signal handlers for production and benchmarks showing RSS growth from 200MB to 2GB.
-
Implementing Content Security Policy (CSP) Headers in Flask to Prevent XSS
Implement CSP headers in Flask using @after_request, nonces, and report-only mode to mitigate XSS risks. Covers directives, common violations, and verification.
-
Implementing OAuth2 with Password Flow in FastAPI: Complete JWT Token Example
Implement OAuth2 password flow in FastAPI with JWT tokens: secure authentication using PyJWT and passlib, including login endpoint, protected routes, and curl tests with a fake user database.
-
Migrate from pyenv to mise: Complete Guide for Python 3.12 to 3.13 Upgrades
Step-by-step guide to migrate from pyenv to mise for Python version management and upgrades from Python 3.12 to 3.13. Mise offers multi-language support, tasks, and project-specific environments.
-
Migrate from requirements.txt to pyproject.toml: 5-Step Process for Flask Applications
Step-by-step guide to migrate Flask apps from requirements.txt to pyproject.toml using Poetry for reproducible builds, efficient installs, and modern packaging standards.
-
Migrating Django Tests from unittest to pytest: 7 Patterns for Using Fixtures Instead of setUp
Migrate Django tests from unittest to pytest: Replace setUp with 7 fixture patterns for faster, parallel tests. Django 5.1 + pytest-django 5.0 examples.
-
Mise Python Installation Times: Comparing Prebuilt Binaries vs Source Compilation
Mise prebuilt binaries vs source compilation: up to 8x faster Python installs in benchmarks on Ubuntu/macOS. Includes setup, workflow, and when to use each.
-
Managing Python 3.11, 3.12, and 3.13 Simultaneously with mise on Windows WSL2
Install and manage Python 3.11, 3.12, and 3.13 simultaneously using mise on Windows WSL2. Covers installation, per-project configuration with .tool-versions, and virtual environment integration.
-
mise vs asdf for Python Development: Performance Benchmarks on M1/M2 Macs
Compare mise and asdf Python version managers on M1/M2 Macs with real benchmarks. Discover which is faster for Python development on Apple Silicon.
-
Comparing Pandas and Polars Performance on DataFrame Operations
Benchmarks comparing Pandas and Polars on groupby, filter, and join operations with 1 million rows. Polars shows significant speedups in some cases. Keywords: pandas polars performance comparison, dataframe benchmarks, python data processing.
-
pip-tools vs poetry vs uv: Which Tool Handles Conflicting setuptools Versions Best?
pip-tools vs Poetry vs uv comparison for conflicting setuptools versions: Benchmarks, resolution strategies, and which Python dependency manager prevents build failures in complex environments.
-
poetry add vs pip install: When Lock Files Prevent Production Dependency Conflicts
poetry add vs pip install comparison: Learn how Poetry lock files prevent production dependency conflicts, ensure reproducible builds, and solve Python dependency hell for reliable deployments.
-
Poetry audit vs pip-audit vs safety: PyPI Vulnerability Coverage Comparison
We compare poetry audit, pip-audit, and safety CLI across vulnerability detection coverage, speed, data sources, output formats, and CI integration. Benchmarks on Flask, Django, and FastAPI projects reveal trade-offs for different workflows.
-
Pydantic v2 Migration in FastAPI: Fixing model_validator Decorator Breaking Changes
Pydantic v2 @model_validator(mode='before') receives model instances in some cases like field assignment. Fixes for FastAPI migration, including code examples and tests.
-
pytest-mock vs unittest.mock: When MagicMock Causes False Positive Test Passes
pytest-mock vs unittest.mock: MagicMock false positives hide KeyError/AttributeError bugs. pytest mocker.patch with autospec=True catches issues early. Python mocking pitfalls, migration guide, strict mocking best practices. Keywords: pytest-mock vs unittest.mock, MagicMock false positive, pytest mocker fixture, mock spec=Dict, python mocking best practices.
-
Python 3.12 EOL Timeline: Planning Your Upgrade to Python 3.13 Before Support Ends
Python 3.12 EOL: Active support ended April 2025, security fixes until Oct 2028. Upgrade to 3.13 guide using mise/asdf/uv: timelines, steps, compatibility, new features.
-
Python 3.13 Performance Gains: Benchmarking FastAPI Endpoints Before and After Upgrade
We benchmark a minimal FastAPI application on Python 3.12 and 3.13 to measure real-world performance differences in RPS and latency for JSON GET and POST endpoints using Locust and uvicorn workers.
-
Python Performance Optimization: Profile, Optimize, and Benchmark Code Speedups
Python performance optimization guide: Profile with cProfile/py-spy, fix memory leaks with memory_profiler, speed up with Numba JIT and multiprocessing. Examples demonstrate up to 5-10x speedups and memory savings in loops, pandas, and APIs. Tested with Python 3.13 tools. Keywords: python performance optimization, optimize python code, python profiling cProfile py-spy, reduce python memory usage, python numba speedup, python multiprocessing performance.
-
Python Version Management (asdf, mise, pyenv)
Compare the best Python version managers: pyenv for Python-specific control, asdf for multi-language support, and mise for speed and versatility. Learn installation, usage, and which to choose in 2026.
-
Reducing Django ORM Query Time by 70% with select_related and prefetch_related
Django ORM N+1 query optimization: select_related for ForeignKey (joins), prefetch_related for ManyToMany/reverse FK (separate queries+caches). Blog example: 501→151 queries, 500ms→150ms (70% faster). django-debug-toolbar verify. Keywords: 'django select_related prefetch_related', 'django n+1 fix', 'django orm performance', 'reduce django queries', 'select_related vs prefetch_related django'.
-
Reducing Docker Image Size from 1.2GB to 145MB for Python FastAPI Applications
Reduce FastAPI Docker images from 1.2 GB to 145 MB using Alpine multistage builds and uv. Includes benchmarks, production Dockerfile, .dockerignore, and pitfalls.
-
Reducing Flask Application Startup Time from 8 Seconds to 800ms
Flask startup optimization: Diagnose slow imports/extensions with py-spy/cProfile, implement lazy loading, disable debug mode, gunicorn preload/app factory. Benchmarks: 8.2s → 0.82s (90% faster). Fix dev restarts, serverless cold starts, k8s deployments.
-
Reducing pytest Suite Runtime from 45 Minutes to 6 Minutes with pytest-xdist Parallelization
pytest-xdist parallel testing: Speed up pytest suite 45min→6min (7.5x) on multi-core CPUs. pytest -n auto detects cores, -n 8 manual. Markers for serial tests, pytest.ini config. Benchmarks Python 3.12, 1000+ tests. Handles DB fixtures.
-
Securing Your Python Supply Chain: Scanning poetry.lock for Compromised Maintainers
A script to check poetry.lock files for packages maintained by known compromised PyPI accounts. Queries PyPI API and cross-references a curated list; suitable for CI/CD integration.
-
Security & Vulnerabilities (CVEs, pip-audit, safety): Python Dependency Auditing Guide
Secure your Python projects: Detect CVEs in dependencies using pip-audit and safety CLI. Installation, usage examples, benchmarks, CI integration for requirements.txt, Poetry, uv. Fix vulnerabilities fast – pip-audit tutorial, safety check best practices 2026.
-
Serving FastAPI Behind Traefik with Automatic HTTPS and Path-Based Routing
Deploy FastAPI behind Traefik using Docker Compose for automatic HTTPS via Let's Encrypt and path-based routing. Covers docker-compose labels, middleware for prefix stripping, and production considerations.
-
Comparing Mise and Docker Python Images for Local Development Performance
Explore using mise instead of Docker for Python images in local development to potentially reduce startup and iteration times. Includes benchmarks from Ubuntu 24.04 and M2 Mac, migration steps, and trade-offs.
-
tox.ini Configuration for Testing Python Packages Across 3.10‑3.13
Example tox.ini for multi‑Python testing (py310‑py313) with pytest, coverage, mypy, and ruff. Includes CI, benchmarks, and pyproject.toml integration.
-
Using pytest Fixtures with FastAPI TestClient for Database Transaction Rollbacks
FastAPI pytest fixtures TestClient database transaction rollbacks: Isolate tests, zero data pollution. SQLAlchemy async sessions, pytest-asyncio override dependency. 500+ tests/s clean state. Code examples, conftest.py fixture, session.begin()/rollback(). Keywords: 'fastapi pytest database testing', 'fastapi testclient fixtures rollback', 'pytest fastapi sqlalchemy transaction rollback', 'fastapi testing isolation', 'pytest fixtures testclient'.
-
uv pip sync: Managing Reproducible Python Environments
uv pip sync synchronizes Python environments exactly to requirements.txt, removing unused packages for reproducibility. Works on system Python without virtualenvs for tools/scripts. Includes setup, usage, lockfiles, benchmarks, comparisons to pip-tools/Poetry.