Python7 min read

Python Security Best Practices

Write secure Python applications.

David Miller
December 18, 2025
0.0k0

Keep your code secure.

Input Validation

```python def process_age(age_str): try: age = int(age_str) if age < 0 or age > 150: raise ValueError("Invalid age") return age except ValueError: raise ValueError("Age must be a valid number")

Don't trust user input user_input = input("Enter age: ") age = process_age(user_input) ```

SQL Injection Prevention

```python import sqlite3

Bad - SQL Injection risk user_id = input("User ID: ") cursor.execute(f"SELECT * FROM users WHERE id = {user_id}")

Good - Use parameterized queries user_id = input("User ID: ") cursor.execute("SELECT * FROM users WHERE id = ?", (user_id,)) ```

Password Hashing

```python from werkzeug.security import generate_password_hash, check_password_hash

Store password password = "user_password" hashed = generate_password_hash(password)

Verify password is_correct = check_password_hash(hashed, password) ```

Environment Variables

```python import os

Bad - hardcoded secrets API_KEY = "secret123"

Good - use environment variables API_KEY = os.getenv("API_KEY") if not API_KEY: raise ValueError("API_KEY not set") ```

Secure File Operations

```python import os

def read_user_file(filename): # Prevent directory traversal base_dir = "/safe/directory" safe_path = os.path.join(base_dir, filename) if not safe_path.startswith(base_dir): raise ValueError("Invalid file path") with open(safe_path, 'r') as f: return f.read() ```

HTTPS Requests

```python import requests

Always verify SSL response = requests.get("https://api.example.com", verify=True)

Don't disable SSL verification # response = requests.get(url, verify=False) # Bad! ```

Remember

- Never trust user input - Use parameterized queries - Hash passwords properly - Keep dependencies updated

#Python#Advanced#Security