Flask is a lightweight Python web framework that relies on Werkzeug for WSGI and Jinja2 for templating. It adopts a micro core design, allowing developers to add extensions for features like database integration or form validation as needed.
Environment Setup
A virtual environment is recommended for isolation:
python -m venv flask_env
source flask_env/bin/activate # Linux / macOS
flask_env\Scripts\activate # Windows
Install Flask inside the environment:
pip install flask
If the default PyPI mirror is slow, use a regional mirror with -i.
Minimal Application
Create a file named server.py:
from flask import Flask
service = Flask(__name__)
@service.route('/')
def home():
return 'Hello from Flask!'
if __name__ == '__main__':
service.run()
Run the script and access http://127.0.0.1:5000. The default port 5000 can be changed:
if __name__ == '__main__':
service.run(host='0.0.0.0', port=8080)
Enable auto‑reloading during development to reflect code changes instantly:
if __name__ == '__main__':
service.run(debug=True)
The debug mode automatically restarts the server when files are modified, so you don't need to manually restart.
Routing Basics
Routes map URLs to view functions. The @app.route decorator defines these mappings. Dynamic segments can be captured with converters:
| Converter | Descripsion |
|---|---|
int |
Accepts integers |
float |
Accepts floating‑point |
path |
Accepts slashes as well |
A more comprehensive example:
from flask import Flask, request
web_app = Flask(__name__)
@web_app.route('/greet')
def greet():
return 'Welcome!'
@web_app.route('/items')
def show_items():
return 'Item list'
# Integer converter
@web_app.route('/item/<int:item_id>/detail')
def item_detail(item_id):
return str(item_id)
# String (default) converter
@web_app.route('/product/<product_name>/info')
def product_info(product_name):
return product_name
# Float converter
@web_app.route('/price/above/<float:threshold>')
def price_filter(threshold):
return str(threshold)
# Path converter
@web_app.route('/catalog/<path:category_path>')
def catalog(category_path):
return category_path
# Allowing GET and POST
@web_app.route('/account', methods=['GET', 'POST'])
def account():
if request.method == 'POST':
return 'Creating account'
return 'Account page'
if __name__ == '__main__':
web_app.run(debug=True)
alter the function names, URL patterns, and variable identifiers. The core ideas remain intact.
Testing the Routes
Start the server and visit these URLs:
http://127.0.0.1:5000/product/chair/infohttp://127.0.0.1:5000/item/42/detailhttp://127.0.0.1:5000/price/above/19.99http://127.0.0.1:5000/catalog/electronics/laptopshttp://127.0.0.1:5000/account(use GET in browser; test POST via tools like curl)
Method Restriction
By default, a route responds to GET requests only. To accept other methods, pass the methods parameter, for example methods=['GET', 'POST', 'PUT']. The view function can then inspect request.method to act accordingly.