Security Best Practices
Input validation, secrets management, and secure coding.
Overview
Master Python security patterns.
Input Validation
import re
from typing import Optional
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(user_input: str) -> str:
# Remove potentially dangerous characters
return re.sub(r'[<>"\']', '', user_input)
def validate_integer(value: str, min_val: int = None, max_val: int = None) -> Optional[int]:
try:
num = int(value)
if min_val is not None and num < min_val:
return None
if max_val is not None and num > max_val:
return None
return num
except ValueError:
return None
Secrets Management
import os
from dotenv import load_dotenv
# Load from .env file
load_dotenv()
# Get secrets
api_key = os.getenv('API_KEY')
db_password = os.getenv('DB_PASSWORD')
# Never hardcode secrets
# BAD: api_key = "secret123"
# GOOD: api_key = os.getenv('API_KEY')
Password Hashing
from werkzeug.security import generate_password_hash, check_password_hash
def hash_password(password: str) -> str:
return generate_password_hash(password)
def verify_password(password: str, hashed: str) -> bool:
return check_password_hash(hashed, password)
# Usage
hashed = hash_password("secure_password123")
print(verify_password("secure_password123", hashed)) # True
Practice
Implement secure authentication for an API.