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,xmlandzipfile. - 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¶
- 8
PY-1Run a Python version that still receives fixes, and upgrade before its end-of-life date. Each feature release gets bug fixes for about two years, then only security fixes until five years after its release. Declare the oldest version the project supports withrequires-python. (Python Developer's Guide, Status of Python versions, Packaging User Guide, requires-python) - 8
PY-2Commit a lock file that pins every direct and transitive dependency, install exactly what it lists in CI and deployments, and audit it for known vulnerabilities in CI. With uv, commituv.lockand install withuv sync --locked; with pip-tools, compile requirements with--generate-hashesand install them withpip install --require-hashes. See general/security.md for dependency updates and provenance. (uv, The lockfile, pip, Secure installs, pip-tools, pip-compile, pip-audit) - 6
PY-3Install each application's dependencies into its own virtual environment, not into the Python that the operating system manages, and treat the environment as disposable. Don't commit or copy it; recreate it from the lock file. (Python, venv, PEP 668, Marking Python base environments as externally managed) - 6
PY-4Describe the project inpyproject.toml, use the src layout, and keep tests in a separatetests/directory. Put metadata,requires-pythonand dependencies in the[project]table rather than insetup.py, and settings for tools such as Ruff, mypy and pytest under[tool]. The src layout helps prevent tests and tools from importing the in-development copy of the code by accident instead of the installed package. (Packaging User Guide, Writing your pyproject.toml, src layout vs flat layout, pytest, Good Integration Practices)
Application structure¶
- 6
PY-5When the domain has real business logic, keep it in plain Python modules that import neither the web framework nor the ORM, and let views, routers, tasks and commands call it through a service layer. A simple CRUD app doesn't need these layers. (Architecture Patterns with Python, Repository pattern, Service layer) - 6
PY-6In FastAPI, split path operations intoAPIRoutermodules by area, and provide shared resources such as database sessions, settings and the current user through dependencies (Depends). Tests can then replace them withapp.dependency_overrides. (FastAPI, Bigger Applications, Dependencies, Testing Dependencies with Overrides)
Types and validation¶
- 8
PY-7Validate all external input at runtime where it enters the application, with Pydantic models (as FastAPI does for request bodies) or with Django forms or Django REST framework serializers, and use only the validated data. Type hints aren't enforced at runtime, so they don't check incoming data. (Python, typing, FastAPI, Request Body, Django, Working with forms, Django REST framework, Serializer validation, Security in Django: Always sanitize user input) - 7
PY-8Annotate the code with type hints and run a type checker, such as mypy or Pyright, in CI, pinned with the other development dependencies. Aim for strict mode: turn it on for new code, and module by module in existing code. (mypy, Using mypy with an existing codebase, mypy, --strict, Pyright, Configuration)
Async code¶
- 8
PY-9Inasynccode, don't call blocking I/O or CPU-heavy functions directly: use async libraries, run blocking calls in a thread withasyncio.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 plaindef, 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-10Run concurrent tasks in anasyncio.TaskGroup, or keep a reference to every task you start withasyncio.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 appliesPRIN-16. (Python, Task groups, asyncio.create_task) - 5
PY-11Write 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 plaindefwhen in doubt. (Python, asyncio, Django, Asynchronous support: Performance, FastAPI, In a hurry?)
Configuration¶
- 9
PY-12In Django, never enableDEBUGin production, loadSECRET_KEYand other secrets from the environment or a file, and runmanage.py check --deployagainst the production settings. Keep the production settings in their own settings module, and serve the app with a production WSGI or ASGI server instead ofrunserver. (Django, Deployment checklist, check --deploy) - 6
PY-13Load configuration into one typed settings object, such as apydantic-settingsBaseSettingsclass, 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¶
- 9
PY-14Never pass untrusted data topickle,eval(),exec()oryaml.load(), or into a shell command withshell=True. Each of them can run arbitrary code: use JSON oryaml.safe_load()for data, and pass subprocess arguments as a list. (Python, pickle, Built-in functions: eval, subprocess: Security considerations, PyYAML documentation) - 6
PY-15Lint and format with Ruff, and runruff checkandruff format --checkin CI and in a pre-commit hook. Ruff replaces Flake8 and its plugins, isort and Black with one fast tool. Extend its rule selection with the rule sets you need, such asS(security) andASYNC. (Ruff, Ruff linter: Rule selection, Ruff formatter, Ruff integrations: pre-commit)
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
--strictand 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'sstrictpaths. ChecksPY-8. - 7
manage.py check --deploy: run it with the production settings and--fail-level WARNING, so that the deployment checks fail CI whenDEBUGis on,SECRET_KEYis short or was generated automatically by Django,ALLOWED_HOSTSis empty, or HTTPS settings are missing. Partly checksPY-12. - 7 pip hash-checking mode and uv
--locked:pip install --require-hashesfails when a requirement isn't pinned and hashed, anduv sync --lockedoruv lock --checkfails whenuv.lockdoesn't matchpyproject.toml. Partly checksPY-2. - 6 Ruff flake8-bandit (
S) rules: S301, S307, S102, S506 and S602 flagpickle,eval(),exec(),yaml.load()andshell=True. Bandit, the standalone security linter, has equivalent checks. ChecksPY-14. - 6 Ruff flake8-async (
ASYNC) rules and RUF006: ASYNC210, ASYNC230 and ASYNC251 flag blocking HTTP calls,open()andtime.sleep()in async functions, and RUF006 flagscreate_task()results that aren't stored. ChecksPY-10, and partlyPY-9andPRIN-16. - 6 Ruff linter exit codes:
ruff checkexits with status 1 on lint violations, andruff format --checkwith a non-zero status on unformatted files, in CI or the pre-commit hook. ChecksPY-15. - 6 pip-audit: audits an environment, requirements files, or a project's
pyproject.tomlandpylock.*.tomlfiles 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 auditaudits the project's dependencies. Partly checksPY-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 asdjango,fastapiorsqlalchemy. Layers contracts check the direction of dependencies between layers. ChecksPY-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.tomland 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.