In Flask, routing is the mechanism to map URLs to functions. These functions are termed as "view functions" and are responsible for returning a response (HTML, JSON, etc.) for the requested URL. The routing system in Flask is quite flexible and allows for various patterns and methods to define URLs.
Here's a basic introduction to Flask app routing:
The most basic route in Flask binds a function to a URL pattern:
from flask import Flask app = Flask(__name__) @app.route('/') def home(): return 'Hello, Flask!' You can add variable sections to a URL by marking sections with <variable_name>. The variable sections are passed as keyword arguments to the view function.
@app.route('/user/<username>') def show_user_profile(username): return f'Hello, {username}!' You can also specify a converter for the variable:
@app.route('/post/<int:post_id>') def show_post(post_id): return f'Post {post_id}' Supported converters include:
int: accepts integersfloat: for floating-point valuespath: accepts slashes as well, useful for pathsBy default, routes respond to GET requests. If you want to handle other HTTP methods like POST, you need to specify them using the methods argument:
from flask import request @app.route('/login', methods=['GET', 'POST']) def login(): if request.method == 'POST': return 'Logging in...' return 'Login form' Flask allows you to build URLs for a specific function using url_for:
from flask import url_for with app.test_request_context(): print(url_for('login')) # Outputs: /login print(url_for('show_user_profile', username='JohnDoe')) # Outputs: /user/JohnDoe If you want to redirect a user to another route, you can use the redirect() function:
from flask import redirect @app.route('/redirect-me') def redirect_me(): return redirect(url_for('home')) You can define custom error pages using error handlers:
@app.errorhandler(404) def page_not_found(error): return 'Page not found', 404
Always remember to run the app at the end:
if __name__ == '__main__': app.run()
This is a simple introduction to routing in Flask. Flask's routing system has more advanced features and capabilities which you can explore in-depth in the official documentation.
android-architecture-navigation dirichlet sweetalert powershell-3.0 arkit rspec hidden-files ssis semantic-ui-react go-reflect