Python Tutorial 0/52 lessons ~6 min read Lesson 46

    Python Security Essentials

    Secure Python services by default: validate input, avoid insecure deserialization, protect secrets, and keep dependencies patched.

    Course progress0%
    Focus
    9 guided sections
    Practice signal
    Examples included
    Career prep
    Interview Q&A included

    Introduction

    Secure Python services by default: validate input, avoid insecure deserialization, protect secrets, and keep dependencies patched.

    Understanding the topic

    Core concepts to understand:

    • Never eval/exec untrusted input.
    • Avoid unsafe YAML loads; use yaml.safe_load.
    • Store secrets in env/secret manager, never in git.
    • Run dependency audits and apply security patches quickly.

    Syntax reference

    Visual flow / code:

    python
    import os, yaml
    from pydantic import BaseModel, ValidationError
    class Payload(BaseModel):
    amount: int
    email: str
    def parse_payload(raw: dict):
    return Payload.model_validate(raw) # validation + coercion
    def load_cfg(path: str):
    with open(path, encoding="utf-8") as f:
    return yaml.safe_load(f) # NEVER yaml.load without safe loader
    DB_URL = os.environ["DB_URL"] # from runtime secret env

    Execution workflow

    1Python Security Essentials Workflow
    1 / 4

    Never eval/exec untrusted input

    Never eval/exec untrusted input.

    Real-world use

    Common Python incidents include leaked API keys, unvalidated payloads, and vulnerable transitive deps. Security hygiene is mostly boring defaults done consistently.

    Best practices

    • Validate all external input.
    • Use pydantic for API boundaries.
    • Rotate secrets.
    • Add pip-audit/safety in CI.

    Common mistakes

    • Committing `.env` files.
    • Blindly trusting user-generated JSON/YAML.
    • Skipping dependency scans.

    Advanced interview questions

    Interview Prep

    Practice concise answers, then expand each card for the explanation.

    3 questions
    1IntermediateQuestionTop Python security risks?+

    Answer

    Common risks are injection (SQL, shell, template) from building commands out of untrusted input, unsafe deserialization such as pickle or unsafe yaml.load, eval and exec on user data, leaked secrets in code or logs, and vulnerable or malicious dependencies. Mitigations include parameterized queries, subprocess with argument lists, input validation, pinned and audited dependencies, and least privilege.

    Follow-up

    Why is shell=True risky in subprocess?
    2BeginnerQuestionWhy avoid eval?+

    Answer

    eval executes arbitrary Python expressions, so any untrusted input can run code with your process's privileges, including importing modules and touching files. Restricting globals and __builtins__ does not make it safe. For literals use ast.literal_eval, and for structured data use json or a real parser.

    Follow-up

    What does ast.literal_eval accept?
    3IntermediateQuestionHow do you handle secrets in prod?+

    Answer

    Keep secrets out of source control and images; inject them at runtime from a secrets manager (such as Vault or a cloud provider's service) or from environment variables set by the platform. Grant each service only the secrets it needs, rotate them, and never log them. Use secrets for generating tokens, and consider a scanner in CI to catch accidental commits.

    Follow-up

    What do you do when a secret is accidentally committed?

    Summary

    In summary: Security is defaults + discipline. Validate input and audit dependencies continuously.

    Ready to mark this lesson complete?Track your journey across the entire course.