Flask Modules - Routes and view functions in Flask

1. **Defining Routes**:

   In Flask, routes define the mapping between URL paths and view functions. To define a route, you can use the `@app.route` decorator. For example:

 from flask import Flask

 app = Flask(__name__)

 @app.route('/')
 def home():
     return 'Welcome to the home page'

   In the example above, `@app.route('/')` defines a mapping between the root URL ('/') and the `home` view function.

2. **View Functions**:

   View functions are Python functions that handle HTTP requests and return HTTP responses. Each route is associated with a view function. View functions typically return HTML pages, JSON data, or other HTTP responses. For example:

   @app.route('/about')
   def about():
       return 'This is the about page'

   In the example above, the `about` view function handles requests with the URL path '/about' and returns the text "This is the about page" as a response.

3. **Dynamic Routes**:

   Flask also supports dynamic routes, allowing you to pass data to view functions through variables in the URL. For example:
 

  @app.route('/user/<username>')
   def user_profile(username):
       return f'User profile for {username}'

   In the example above, `<username>` is a dynamic part that can match any username. This username is passed as a parameter to the `user_profile` view function.

4. **HTTP Methods**:

   You can use different HTTP methods (GET, POST, PUT, DELETE, etc.) to define routes so that view functions can handle specific types of HTTP requests. By default, routes use the GET method. For example:

   @app.route('/submit', methods=['POST'])
   def submit_form():
       # Handle form submission
       return 'Form submitted successfully'

   In the example above, the `submit_form` view function only handles POST requests.

5. **URL Building**:   

   Flask provides the `url_for` function to build URLs for routes. This helps dynamically generate URLs for routes instead of hardcoding them. For example:

   from flask import url_for

   url = url_for('about')

   The above code will generate the URL associated with the 'about' view function, which is useful for generating links in templates.

猜你喜欢

转载自blog.csdn.net/Alexandra_Zero/article/details/132690834