Full Stack Python: Protecting Your Application from SQL Injection
π What Is SQL Injection?
SQL Injection occurs when attackers manipulate SQL queries by injecting malicious input into your application's database commands, potentially gaining unauthorized access to data or even executing arbitrary SQL code.
Example of bad practice (vulnerable):
python
Copy
Edit
# ❌ Do NOT do this
username = request.form['username']
cursor.execute(f"SELECT * FROM users WHERE username = '{username}'")
✅ Safe Practices to Prevent SQL Injection
1. Use Parameterized Queries (Safe with Raw SQL)
Always use placeholders instead of string interpolation:
python
Copy
Edit
# ✅ SAFE: parameterized query with SQLite or psycopg2
cursor.execute("SELECT * FROM users WHERE username = %s", (username,))
For SQLite: use ? as placeholder
For PostgreSQL/MySQL (psycopg2, MySQLdb): use %s
2. Use an ORM (Object Relational Mapper)
Frameworks like SQLAlchemy, Django ORM, or Tortoise ORM abstract SQL generation safely.
✅ SQLAlchemy example:
python
Copy
Edit
user = session.query(User).filter(User.username == username).first()
✅ Django example:
python
Copy
Edit
user = User.objects.get(username=username)
ORMs escape parameters by default—a huge protection boost.
3. Avoid Dynamic SQL Unless Absolutely Necessary
If you must use dynamic SQL (e.g., for table names), never interpolate user input directly.
Instead, validate against a whitelist:
python
Copy
Edit
valid_columns = ['name', 'email', 'created_at']
if sort_by in valid_columns:
query = f"SELECT * FROM users ORDER BY {sort_by}"
else:
raise ValueError("Invalid sort key")
4. Input Validation & Sanitization (Defense-in-Depth)
Validate input types, lengths, formats
Reject unexpected characters or patterns
Sanitize input (though parameterization is always better)
5. Use Web Framework Features
Frameworks like Flask, FastAPI, Django, etc., provide tools to manage user input safely.
Example with FastAPI:
python
Copy
Edit
from fastapi import FastAPI, Query
@app.get("/users/")
def get_users(limit: int = Query(10, ge=1, le=100)):
# ORM or safe query follows
6. Turn On SQL Logging During Development
Watch your queries in the dev environment:
SQLAlchemy: echo=True in engine config
Django: django.db.connection.queries
Helps you spot unsafe query patterns
π Summary: Secure Your Stack
Layer Strategy
Database Access Use parameterized queries / ORM
Input Handling Validate & sanitize input
Framework Usage Leverage built-in protections
Logging Monitor SQL during development
π§° Bonus: Use Tools to Scan for Vulnerabilities
Bandit – Static analysis for Python code
SQLMap – To test your app against SQL injection
OWASP ZAP – General web vulnerability scanner
Learn Full Stack Python Course in Hyderabad
Read More
How to Use JWT (JSON Web Tokens) for API Authentication in Python
Introduction to Python for Full Stack Developers
Implementing User Authentication in Django
Visit Our IHUB Talent Training Institute in Hyderabad
Comments
Post a Comment