python-backend
/

Python Security – Writing Secure & Robust Code

Last Sync: Today

On this page

6
0%
5 min read
Remaining
5 minleft

Click any section to jump — progress syncs automatically

python-backend

Python Security – Writing Secure & Robust Code

Security-First Python Development

Security in Python involves more than just fixing bugs; it's about architectural decisions. Whether you are building an AI-powered Flutter builder or a high-performance REST API, you must account for the OWASP Top 10 vulnerabilities. In Python, this primarily means focusing on input validation, secure dependency management, and protecting sensitive data.

  1. Preventing Injections

Injections occur when untrusted data is sent to an interpreter as part of a command. This is most common in SQL queries, but can also happen with OS commands (os.system) and dynamic code execution (eval()).

PythonRead-only
1
# ❌ DANGEROUS: eval() can execute any string as code
# user_input = "__import__('os').system('rm -rf /')"
# eval(user_input)

# ✅ SAFE: Use literal_eval for safely parsing strings into Python types
from ast import literal_eval
try:
    data = literal_eval("[1, 2, 3]")
except (ValueError, SyntaxError):
    print("Invalid input")

  1. Secure Credential Management

Never hardcode API keys (like Gemini API keys), database passwords, or secret tokens in your source code. Use environment variables and .env files (which should be added to .gitignore).

PythonRead-only
1
import os
from dotenv import load_dotenv

load_dotenv() # Loads variables from .env

# Accessing sensitive data safely
GEMINI_API_KEY = os.getenv("GEMINI_API_KEY")
DATABASE_URL = os.getenv("DATABASE_URL")

  1. Data Encryption & Hashing

Never store passwords in plain text. Always use a strong, salted hashing algorithm like Argon2 or bcrypt. For general data encryption, use the cryptography library rather than rolling your own crypto logic.

PythonRead-only
1
import bcrypt

# Hashing a password
password = b"super_secret_123"
hashed = bcrypt.hashpw(password, bcrypt.gensalt())

# Checking a password
if bcrypt.checkpw(password, hashed):
    print("Login Successful")

The Security Layer Cake

Effective security requires multiple layers, from the environment level down to the code execution level.

Security Checklist for Python Apps

VulnerabilityPython SolutionTool/Library
SQL InjectionParameterized Queries / ORMsSQLAlchemy, Django ORM
Insecure SecretsEnvironment Variablespython-dotenv, HashiCorp Vault
Vulnerable DepsDependency Auditingsafety, pip-audit
XSS (Templates)Auto-escapingJinja2 (Flask), DTL (Django)
Weak HashingModern Hashing Algorithmsbcrypt, passlib
Broken AuthJWT / OAuth2PyJWT, FastAPI Security

Test Your Knowledge

Q1
of 3

Which module should be strictly avoided for untrusted data due to remote code execution risks?

A
json
B
pickle
C
requests
D
logging
Q2
of 3

What is the best way to prevent SQL Injection in Python?

A
Replacing single quotes with double quotes
B
Using f-strings to build queries
C
Using parameterized queries or an ORM
D
Encoding the query in Base64
Q3
of 3

Why is it dangerous to hardcode API keys in your repository?

A
It makes the file size larger
B
The keys can be stolen by anyone with access to the history, even if deleted later
C
Python won't be able to read them
D
It slows down the application performance

Frequently Asked Questions

What is the 'Safety' package?

Safety is a CLI tool that checks your installed dependencies against a database of known security vulnerabilities. It's a best practice to run 'safety check' as part of your CI/CD pipeline.

Should I use the built-in 'hashlib' for passwords?

No. hashlib provides raw algorithms like SHA-256 which are too fast and easily crackable for passwords. Use 'bcrypt' or 'Argon2' because they are designed to be slow and computationally expensive for attackers.

Is Pickle safe to use for data serialization?

No. The 'pickle' module is not secure. It can be exploited to execute arbitrary code during unpickling. Only unpickle data you trust completely, or preferably use JSON for cross-language data exchange.

Previous

python authorization

Next

python async

Related Content

Need help?

Explore our comprehensive docs or start a chat with our tech experts.