Security is one of the most critical aspects of web development. Poor security practices can lead to data breaches, unauthorized access, and cyber attacks. In this tutorial, we’ll cover the best security practices for Flask and Django web applications.
Using outdated libraries can introduce vulnerabilities. Always keep your dependencies updated:
pip list --outdated
pip install --upgrade <package-name>pip list --outdated
pip install --upgrade djangoYou can also use pip-audit to check for vulnerabilities:
pip install pip-audit
pip-auditNever store API keys, database credentials, or secret keys in code. Instead, use environment variables.
import os
SECRET_KEY = os.getenv("SECRET_KEY", "default-secret-key")Set it in your .env file:
SECRET_KEY=mysecurekey123import os
SECRET_KEY = os.environ.get("SECRET_KEY", "default-secret-key")Use python-dotenv to load environment variables:
pip install python-dotenvDATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': os.getenv("DB_NAME"),
'USER': os.getenv("DB_USER"),
'PASSWORD': os.getenv("DB_PASSWORD"),
'HOST': os.getenv("DB_HOST"),
'PORT': '5432',
}
}SQL injection is one of the most common attacks on web applications.
cursor.execute(f"SELECT * FROM users WHERE username = '{username}'")User.objects.filter(username=username).first() # Django ORM
db.session.query(User).filter_by(username=username).first() # Flask SQLAlchemyXSS attacks inject malicious scripts into web pages.
<p>{{ user_input }}</p> <!-- Secure --><p>{{ user_input }}</p> <!-- Secure -->But be careful when using |safe:
<p>{{ user_input | safe }}</p> <!-- Risky -->CSRF (Cross-Site Request Forgery) tricks users into submitting unauthorized actions.
Make sure your templates include:
<form method="POST">
{% csrf_token %}
<input type="submit" value="Submit">
</form>pip install flask-wtfThen, add CSRF protection:
from flask_wtf.csrf import CSRFProtect
csrf = CSRFProtect(app)from django.contrib.auth.hashers import make_password
hashed_password = make_password("mypassword")from werkzeug.security import generate_password_hash
hashed_password = generate_password_hash("mypassword")SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = Trueapp.config['SESSION_COOKIE_SECURE'] = True
app.config['REMEMBER_COOKIE_SECURE'] = TrueAlways encrypt data in transit with HTTPS.
pip install django-sslserverEnable SECURE_SSL_REDIRECT in settings:
SECURE_SSL_REDIRECT = TrueUse Flask-Talisman:
pip install flask-talismanfrom flask_talisman import Talisman
Talisman(app)Clickjacking tricks users into clicking hidden UI elements.
X_FRAME_OPTIONS = 'DENY'Talisman(app, frame_options="DENY")pip install bandit
bandit -r myproject/By implementing these security best practices, you can protect your Flask and Django applications from common vulnerabilities.
Sign in to join the discussion and post comments.
Sign inPython Basics
Python is a powerful, high-level programming language known for its simplicity and versatility. It is widely used in various fields, including web development, data science, artificial intelligence, automation, and more. This tutorial series is designed to take you from the basics of Python to more advanced topics, ensuring a strong foundation in programming.
Object-Oriented Programming (OOP) in Python
Learn the fundamentals of Object-Oriented Programming (OOP) in Python, including classes, objects, inheritance, polymorphism, encapsulation, and more. Understand how OOP enhances code reusability, scalability, and organization.