Flask App Routing

Flask App Routing

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:

1. Basic Route:

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!' 

2. Variable Rules:

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 integers
  • float: for floating-point values
  • path: accepts slashes as well, useful for paths

3. HTTP Methods:

By 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' 

4. URL Building:

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 

5. Redirection:

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')) 

6. Error Handlers:

You can define custom error pages using error handlers:

@app.errorhandler(404) def page_not_found(error): return 'Page not found', 404 

Final Note:

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.


More Tags

android-architecture-navigation dirichlet sweetalert powershell-3.0 arkit rspec hidden-files ssis semantic-ui-react go-reflect

More Programming Guides

Other Guides

More Programming Examples