Python26 min read

Python Security Best Practices

Learn practical security habits in Python: validate input, prevent SQL injection, protect secrets, hash passwords, and avoid common vulnerabilities in real apps.

David Miller
August 3, 2025
9.7k287

Security is not optional. Even small apps can be attacked.

        This lesson teaches safe habits that every developer should follow.
        
        ## 1) Validate input (never trust user input)
        
        ```python
        def parse_age(age_str: str) -> int:
            try:
                age = int(age_str)
            except ValueError:
                raise ValueError("Age must be a number")
        
            if age < 0 or age > 150:
                raise ValueError("Age out of range")
        
            return age
        ```
        
        ## 2) Prevent SQL injection (parameterized queries)
        
        ```python
        import sqlite3
        
        conn = sqlite3.connect("app.db")
        cur = conn.cursor()
        
        user_id = input("User ID: ")
        
        # Good: safe parameterization
        cur.execute("SELECT * FROM users WHERE id = ?", (user_id,))
        ```
        
        ## 3) Hash passwords (never store plain text)
        
        ```python
        from werkzeug.security import generate_password_hash, check_password_hash
        
        password = "user_password"
        hashed = generate_password_hash(password)
        
        print(check_password_hash(hashed, "user_password"))
        ```
        
        ## 4) Keep secrets out of code (use env vars)
        
        ```python
        import os
        
        api_key = os.getenv("API_KEY")
        if not api_key:
            raise ValueError("API_KEY not set")
        ```
        
        ## 5) Safe file paths (avoid directory traversal)
        
        ```python
        import os
        
        def safe_read(filename: str) -> str:
            base_dir = "/safe/directory"
            safe_path = os.path.abspath(os.path.join(base_dir, filename))
        
            if not safe_path.startswith(os.path.abspath(base_dir)):
                raise ValueError("Invalid path")
        
            with open(safe_path, "r") as f:
                return f.read()
        ```
        
        ## 6) HTTPS verification (do not disable SSL)
        
        ```python
        import requests
        
        response = requests.get("https://api.example.com", timeout=10, verify=True)
        ```
        
        ## Graph: security mindset
        
        ```mermaid
        flowchart LR
          A[User input] --> B[Validate + sanitize]
          B --> C[Process safely]
          C --> D[Store safely]
          D --> E[Log safely]
        ```
        
        ## Remember
        
        - Validate all input
        - Use parameterized SQL
        - Hash passwords, never store plain
        - Keep secrets in env vars
        - Don’t log sensitive data
        
#Python#Advanced#Security