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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值