Flask
Routing
Define routes with methods and dynamic parameters.
By EZ4Code Team
routingmethods
Code
from flask import Flask, request
app = Flask(__name__)
@app.route("/")
def index():
return "Hello, Flask!"
@app.route("/user/<username>")
def show_user(username):
return f"User: {username}"
@app.route("/post/<int:post_id>")
def show_post(post_id):
return f"Post #{post_id}"
@app.route("/api", methods=["GET", "POST"])
def api():
if request.method == "POST":
return "created", 201
return "list"
if __name__ == "__main__":
app.run(debug=True)Explanation
The @app.route decorator maps a URL to a view function. Converters like <int:post_id> validate and cast URL segments, while the methods argument restricts accepted HTTP verbs. Returning a tuple like (body, status_code) sets the response status.
More Flask Snippets
Request and Response
Access request data and build custom responses.
Jinja2 Templates
Render templates with context and template inheritance.
Blueprints
Organize an app into modular blueprints.
Session
Store per-user data in signed session cookies.
Error Handling
Register custom error handlers for HTTP exceptions.
Flask-SQLAlchemy
Define models and query them with Flask-SQLAlchemy.