Learn Python
Secure Python
Protect secrets, inputs, SQL, subprocesses, files and dependencies.
Read secrets from environment variables or a secret manager—never source code or Git.
import os
api_key = os.environ.get("MY_APP_API_KEY")
if not api_key:
raise RuntimeError("MY_APP_API_KEY is missing")Validate at boundaries
Everything from users, files, networks and databases may be wrong. Validate type, format, length, size and allowed values before passing data deeper into the program.
Avoid dangerous shortcuts
- Parameterize SQL instead of formatting strings.
- Never run external text through
eval()orexec(). - Do not load untrusted
pickledata. - Avoid
shell=Truewith dynamic commands. - Check extracted archive paths for path traversal.
- Never log passwords, tokens or sessions.
Use Argon2 or bcrypt for password hashing, not ordinary SHA-256. Keep dependencies locked, updated and scanned for known vulnerabilities.
Security review
Trace data from input to output. Ask who may perform the action, which resources the input can reach, and what happens if the request is repeated or extremely large.