Skip to content

Python

Scope: applications and back-end services written in Python 3, such as web APIs built with FastAPI or Django, background workers and command-line tools, on Python versions that still receive fixes. For configuration, health checks, telemetry and resilience, follow general/operations-reliability.md; for secrets, authorization and the supply chain, general/security.md; for test strategy and architecture tests, general/testing-delivery.md; for container images, Docker. The rules here cover what is specific to Python.

Entries are sorted by score from 1 to 10 (criteria): 9โ€“10 start here or strongly recommended, 6โ€“8 recommended, 1โ€“5 further reading or conditional.

Adopted references

  • 9 Python Packaging User Guide (PyPA): the baseline for project metadata, pyproject.toml, virtual environments and installing packages. Its tool recommendations name the recognised tools for each task, and the deprecated ones to avoid.
  • 8 Deployment checklist (Django): the settings to review before deploying a Django project, for security, performance, operations and error reporting.
  • 8 Security in Django (Django): the built-in protections against cross-site scripting, CSRF, SQL injection, clickjacking and host header attacks, plus HTTPS, sessions and user-uploaded content, and their limits.
  • 7 Developing with asyncio (Python docs): debug mode, threads, blocking code, and finding never-awaited coroutines and never-retrieved exceptions.
  • 7 Security Considerations (Python docs): the standard-library modules with security caveats, such as pickle, random, subprocess, tempfile, xml and zipfile.
  • 7 Static Typing with Python (Python typing docs): tutorials, guides, reference and the typing specification that type checkers share.
  • 7 Architecture Patterns with Python (Harry Percival and Bob Gregory, free online): dependency inversion, the repository, service layer and unit of work patterns, and event-driven architecture, with an appendix for Django. Use it when the domain is complex enough to justify the layers.
  • 6 Deployments Concepts (FastAPI): HTTPS, running on startup, restarts, worker processes, memory and pre-start steps, whichever way you deploy a FastAPI app.
  • 6 Django Security Cheat Sheet (OWASP): authentication, key management, security headers, cookies, CSRF, XSS and HTTPS settings for Django.
  • 6 PEP 8, Style Guide for Python Code: the standard conventions for naming, code layout and imports.

Key rules

Project setup and dependencies

Application structure

Types and validation

Async code

  • 8 PY-9 In async code, don't call blocking I/O or CPU-heavy functions directly: use async libraries, run blocking calls in a thread with asyncio.to_thread() (in Django, sync_to_async()), and run CPU-heavy work in an executor such as a process pool. A blocking call stalls every other task on the event loop. In FastAPI, declare endpoints and dependencies that use blocking libraries with plain def, which FastAPI runs in a thread pool. (Python, Running blocking code, asyncio.to_thread, FastAPI, Concurrency and async / await, Django, Async adapter functions)
  • 7 PY-10 Run concurrent tasks in an asyncio.TaskGroup, or keep a reference to every task you start with asyncio.create_task() until it finishes. The event loop keeps only weak references to tasks, so an unreferenced task can be garbage-collected before it's done. This is how asyncio applies PRIN-16. (Python, Task groups, asyncio.create_task)
  • 5 PY-11 Write async code only where a service waits on many I/O operations at once, such as long-lived connections or calls fanned out to other services. Otherwise keep it synchronous. Django advises enabling ASGI only if the project has asynchronous code, and FastAPI advises plain def when in doubt. (Python, asyncio, Django, Asynchronous support: Performance, FastAPI, In a hurry?)

Configuration

  • 9 PY-12 In Django, never enable DEBUG in production, load SECRET_KEY and other secrets from the environment or a file, and run manage.py check --deploy against the production settings. Keep the production settings in their own settings module, and serve the app with a production WSGI or ASGI server instead of runserver. (Django, Deployment checklist, check --deploy)
  • 6 PY-13 Load configuration into one typed settings object, such as a pydantic-settings BaseSettings class, so that missing or malformed values raise a validation error when the settings load. Environment variables are always strings; the settings class converts and validates them, and can also read secrets files. In FastAPI, provide it through a dependency so that tests can override it. (FastAPI, Settings and Environment Variables, Pydantic, Settings Management)

Code quality and security

How to enforce

Tools that check the key rules above automatically, in CI, the IDE or a commit hook. "Partly" means the tool covers only some of what the rule asks.

  • 7 mypy --strict and Pyright strict mode: fail CI on type errors. Both can apply strict checking to selected modules first, through mypy's per-module options or Pyright's strict paths. Checks PY-8.
  • 7 manage.py check --deploy: run it with the production settings and --fail-level WARNING, so that the deployment checks fail CI when DEBUG is on, SECRET_KEY is short or was generated automatically by Django, ALLOWED_HOSTS is empty, or HTTPS settings are missing. Partly checks PY-12.
  • 7 pip hash-checking mode and uv --locked: pip install --require-hashes fails when a requirement isn't pinned and hashed, and uv sync --locked or uv lock --check fails when uv.lock doesn't match pyproject.toml. Partly checks PY-2.
  • 6 Ruff flake8-bandit (S) rules: S301, S307, S102, S506 and S602 flag pickle, eval(), exec(), yaml.load() and shell=True. Bandit, the standalone security linter, has equivalent checks. Checks PY-14.
  • 6 Ruff flake8-async (ASYNC) rules and RUF006: ASYNC210, ASYNC230 and ASYNC251 flag blocking HTTP calls, open() and time.sleep() in async functions, and RUF006 flags create_task() results that aren't stored. Checks PY-10, and partly PY-9 and PRIN-16.
  • 6 Ruff linter exit codes: ruff check exits with status 1 on lint violations, and ruff format --check with a non-zero status on unformatted files, in CI or the pre-commit hook. Checks PY-15.
  • 6 pip-audit: audits an environment, requirements files, or a project's pyproject.toml and pylock.*.toml files against the PyPI and OSV vulnerability databases, and exits with code 1 when it finds a known vulnerability. It has an official GitHub Action and a pre-commit hook. In uv projects, uv audit audits the project's dependencies. Partly checks PY-2.
  • 6 Import Linter forbidden contracts: lint-imports, in CI or as a pre-commit hook, reports domain modules that import forbidden modules, including external packages such as django, fastapi or sqlalchemy. Layers contracts check the direction of dependencies between layers. Checks PY-5.

Tutorials and further reading

  • 7 Writing your first Django app (Django): the official eight-part tutorial, covering models, views, templates, forms, testing, static files and the admin.
  • 7 Tutorial - User Guide (FastAPI): builds up FastAPI's features step by step, from path operations and request bodies to dependencies, security, databases and testing.
  • 6 The Python Tutorial (Python docs): the official introduction to the language and its standard library.
  • 6 Working on projects (uv): creating a project, managing dependencies, the lock file and running commands with uv.
  • 6 Packaging Python Projects (PyPA): a small project with pyproject.toml and the src layout, built and uploaded to a package index.
  • 5 Type hints cheat sheet (mypy): annotation syntax for variables, functions, classes, generics and async code at a glance.