Python Docs
Flask
Flask is a lightweight Python web framework — simple to start, flexible to grow. You start with a small core and add only the components you need, which makes Flask ideal for APIs, microservices, and small to medium web applications.
Why Flask?
- Minimal and easy to understand.
- No strict project structure — you design it.
- Choose your own ORM, auth, and extensions.
- Perfect for REST APIs and microservices.
- Great for learning how web frameworks work internally.
Install
Install Flask using pip:
Command
pip install flask
Hello, World
A minimal Flask application that responds with plain text at the root URL (/).
Example: Basic App
from flask import Flask
app = Flask(__name__)
@app.get('/')
def home():
return 'Hello Flask'
if __name__ == '__main__':
app.run(debug=True)How it works:
Flask(__name__)creates the app instance.@app.get('/')maps the URL/to thehomefunction.debug=Trueenables hot reload and debugger (development only).
Templates (Jinja2)
Flask uses the Jinja2 templating engine to render dynamic HTML pages. You pass variables from the view to the template.
Example: Route with Template
# app.py
from flask import Flask, render_template
app = Flask(__name__)
@app.get('/hello/<name>')
def hello(name):
return render_template('hello.html', name=name)<!-- templates/hello.html -->
<!doctype html>
<h1>Hello {{ name }}!</h1>Template flow:
Request: /hello/Alice
→ hello(name='Alice')
→ render_template('hello.html', name='Alice')
→ HTML: "Hello Alice!"Notes & Best Practices
- Use blueprints as your app grows to split routes into modules (e.g.,
auth,api,dashboard). - Set environment variables like
FLASK_APPandFLASK_ENVfor CLI usage:export FLASK_APP=app.py export FLASK_ENV=development flask run
- For production, disable
debugand use a WSGI server like Gunicorn or uWSGI behind Nginx. - For APIs, consider using extensions like
Flask-RESTfulorFlask-Smorest.