Python Security — Protecting Your Code
Security is critical for any application. Python provides tools and patterns to protect against common vulnerabilities.
Learning Objectives
- Prevent SQL injection and XSS
- Manage secrets and credentials securely
- Validate and sanitize user input
- Apply security best practices
SQL Injection Prevention
import sqlite3
# DANGEROUS — never do this
# cursor.execute(f"SELECT * FROM users WHERE name = '{user_input}'")
# SAFE — use parameterized queries
cursor.execute("SELECT * FROM users WHERE name = ?", (user_input,))
Secrets Management
import os
from pathlib import Path
# Don't hardcode secrets
# Bad: API_KEY = "sk-1234567890"
# Good: use environment variables
API_KEY = os.environ.get("API_KEY")
if not API_KEY:
raise ValueError("API_KEY not set")
# Better: use .env files with python-dotenv
from dotenv import load_dotenv
load_dotenv()
API_KEY = os.environ["API_KEY"]
Input Validation
import re
def validate_email(email: str) -> bool:
pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
return bool(re.match(pattern, email))
def sanitize_input(text: str) -> str:
return re.sub(r'[<>"\']', '', text)
Password Hashing
import bcrypt
password = "my_secret_password".encode()
hashed = bcrypt.hashpw(password, bcrypt.gensalt())
if bcrypt.checkpw(password, hashed):
print("Password matches")
HTTPS and TLS
import requests
# Always use HTTPS for sensitive requests
response = requests.get("https://api.example.com/data", verify=True)
Key Takeaways
- Always use parameterized queries (never f-strings for SQL)
- Store secrets in environment variables, not code
- Validate and sanitize all user input
- Use bcrypt for password hashing
- Always use HTTPS for sensitive data