Flask
This Flask cheatsheet provides a concise
-
What is Flask?
- Flask is a lightweight Python web framework used for building web applications.
- It is micro: minimal core, highly extensible with plugins.
- Follows WSGI (Web Server Gateway Interface) standard.
-
Why Flask?
- Simple and easy to learn.
- Flexible and minimalistic.
- Large community and many extensions.
- Ideal for small to medium web applications or APIs.
-
Flask vs Django
Feature Flask Django Type Microframework Full-stack framework Built-in Admin ❌ ✅ ORM Optional (SQLAlchemy) Built-in (Django ORM) Flexibility High Medium Learning Curve Easy Moderate
2. Setting Up Flask
Prerequisites
- Python installed (3.8+ recommended)
- Pip for package management
Step 1: Create Virtual Environment
python -m venv venv
Step 2: Activate Virtual Environment
- Windows:
venv\\Scripts\\activate
- Linux/macOS:
source venv/bin/activate
Step 3: Install Flask
pip install flask
Step 4: Verify Installation
python -m flask --version
3. Creating Your First Flask App
Step 1: Basic App
from flask import Flask app = Flask(__name__) @app.route('/') def home(): return "Hello, Flask!" if __name__ == '__main__': app.run(debug=True)
- Run app
python app.py
- Open http://127.0.0.1:5000/ in browser.
4. Flask App Structure
A basic Flask project structure:
myflaskapp/
app.py
templates/
home.html
static/
style.css
- app.py – Main app file
- templates/ – HTML templates
- static/ – CSS, JS, images
5. Routing in Flask
- Basic Routing
@app.route('/') def home(): return "Home Page" @app.route('/about') def about(): return "About Page"
- Dynamic Routing
@app.route('/user/<username>') def user_profile(username): return f"User: {username}"
- Type converters
@app.route('/post/<int:id>') def post(id): return f"Post ID: {id}"
6. HTTP Methods
- GET and POST
from flask import request @app.route('/login', methods=['GET', 'POST']) def login(): if request.method == 'POST': username = request.form['username'] return f"Logged in as {username}" return ''' <form method="post"> <input type="text" name="username"> <input type="submit"> </form> '''
- Other HTTP methods: PUT, DELETE (used in APIs)
7. Templates (Jinja2)
- Create Template: templates/home.html
<!DOCTYPE html> <html> <head> <title>{{ title }}</title> </head> <body> <h1>Welcome, {{ name }}!</h1> </body> </html>
- Render Template
from flask import render_template @app.route('/') def home(): return render_template('home.html', title="Home Page", name="Uday")
-
Template Features
-
Variables: `{{ variable }}`
-
Conditionals:
{% if name == "Uday" %} <p>Hello Uday!</p> {% endif %}
* Loops: ```html {% for item in items %} <li>{{ item }}</li> {% endfor %} -
8. Static Files (CSS, JS, Images)
- Folder Structure
static/
css/style.css
js/script.js
images/logo.png
- Use in template
<link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}" />
9. Flask Forms
- Simple Form Handling
from flask import request, redirect, url_for @app.route('/contact', methods=['GET', 'POST']) def contact(): if request.method == 'POST': name = request.form['name'] return f"Hello {name}!" return render_template('contact.html')
- Template
<form method="post"> <input type="text" name="name" /> <input type="submit" /> </form>
- CSRF Protection
- Use Flask-WTF extension
pip install flask-wtf
10. Flask Models & Database
- Use SQLAlchemy ORM
pip install flask_sqlalchemy
- Setup Database
from flask_sqlalchemy import SQLAlchemy app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///students.db' db = SQLAlchemy(app)
- Create Model
class Student(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(100)) email = db.Column(db.String(100))
- Create Database
from app import db db.create_all()
- CRUD Operations
# Create s = Student(name="Uday", email="uday@example.com") db.session.add(s) db.session.commit() # Read Student.query.all() Student.query.filter_by(name="Uday").first() # Update s.name = "Uday Raut" db.session.commit() # Delete db.session.delete(s) db.session.commit()
11. Flask Blueprints (Modular Apps)
- Create Blueprint
from flask import Blueprint auth = Blueprint('auth', __name__) @auth.route('/login') def login(): return "Login Page"
- Register Blueprint in app.py
from auth import auth app.register_blueprint(auth, url_prefix='/auth')
12. Flask Authentication
- User Model
from werkzeug.security import generate_password_hash, check_password_hash password_hash = generate_password_hash('123456') check_password_hash(password_hash, '123456') # returns True
- Flask-Login
pip install flask-login
- Manage user sessions, login/logout, and access control.
13. Flask RESTful API
- Use Flask-RESTful
pip install flask-restful
- Example API
from flask_restful import Api, Resource api = Api(app) class StudentAPI(Resource): def get(self): return {"students": ["Uday", "John"]} api.add_resource(StudentAPI, '/api/students')
- JSON Response
from flask import jsonify @app.route('/data') def data(): return jsonify({"name": "Uday", "age": 20})
14. Flask Sessions & Cookies
- Sessions
from flask import session app.secret_key = 'secret' session['username'] = 'Uday' session.get('username')
- Cookies
from flask import make_response resp = make_response("Setting cookie") resp.set_cookie('userID', '123') return resp
15. Error Handling
- 404 Page
@app.errorhandler(404) def page_not_found(e): return render_template('404.html'), 404
- Custom Error Pages
- Handle 500, 403 errors similarly.
16. Flask Middleware (Before/After Request)
@app.before_request def before_request_func(): print("Before Request") @app.after_request def after_request_func(response): print("After Request") return response
17. Flask Email
- Using Flask-Mail
pip install flask-mail
- Send emails via SMTP (Gmail, Outlook)
18. Testing in Flask
- Unit Testing
import unittest from app import app class FlaskTestCase(unittest.TestCase): def test_home(self): tester = app.test_client() response = tester.get('/') self.assertEqual(response.status_code, 200)
19. Deployment
- Prepare for Production
- debug=False in app.run()
- Use Gunicorn for WSGI server:
pip install gunicorn gunicorn app:app
-
Deploy Options
- Heroku
- AWS EC2
- PythonAnywhere
- Docker
-
Static Files in Production
- Use WhiteNoise or serve via Nginx
20. Advanced Features
-
Flask Extensions
- Flask-WTF – Forms
- Flask-Login – Authentication
- Flask-Mail – Emails
- Flask-Migrate – Database migrations
- Flask-Caching – Caching
-
Background Tasks
- Using Celery + Redis for asynchronous jobs
-
WebSockets
- Use Flask-SocketIO for real-time communication