flask
  1. flask-app-routing

App Routing (Basics of Flask)

Syntax

The routing in Flask is handled by using the route() decorator. It binds a function to a URL path and accepts the HTTP methods as an argument.

from flask import Flask

app = Flask(__name__)

@app.route('/path', methods=['GET'])
def function_name():
    # code here
  • app: An instance of the Flask class that will handle the routing of the application.
  • @app.route: A decorator that is used to associate the function with a specific URL.
  • '/': The URL path.
  • methods=['GET']: Specifies the HTTP methods that can be used to access this URL.
  • def function_name():: The name of the function that is associated with this URL.

Example

from flask import Flask

app = Flask(__name__)

@app.route('/')
def hello_world():
    return 'Hello, World!'

Output

When you navigate to the localhost:5000/ URL, the hello_world() function will be called and the message Hello, World! will be displayed in the browser.

Explanation

The route() decorator associates a function with a specific URL. When the user navigates to that URL, the function is called and its return value is displayed in the browser. In the example above, the hello_world() function is associated with the / URL. When the user navigates to that URL, the function is called and it returns the string 'Hello, World!'. This string is then displayed in the browser.

Use

The routing in Flask allows you to create URLs for different pages of your web application. These URLs can be used to navigate between different pages and to access different functionalities of your web application.

Important Points

  • The URL paths can contain variables that can be passed as arguments to the associated function.
  • You can associate the same function with multiple URLs by using multiple route() decorators.
  • The order in which the route() decorators are used is important. Flask matches the URL paths in the order in which they were defined.

Summary

In this tutorial, we learned about the basics of App Routing in Flask. We saw how the route() decorator can be used to associate a function with a specific URL and how that function can be called when the user navigates to that URL. We also saw some important points and use cases for routing in Flask.

Published on: