Python Security — Protecting Your Code

Python AdvancedSecurityFree Lesson

Advertisement

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

  1. Always use parameterized queries (never f-strings for SQL)
  2. Store secrets in environment variables, not code
  3. Validate and sanitize all user input
  4. Use bcrypt for password hashing
  5. Always use HTTPS for sensitive data

Advertisement

Need Expert Python Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement