Flask 路由是构建 Web 应用程序的关键部分。它允许您定义 URL 和相应的处理函数。以下是一些关于 Flask 路由的基础知识。

路由规则

Flask 使用路由规则来匹配 URL。以下是一个简单的路由示例:

@app.route('/')
def index():
    return '首页'

在这个例子中,当访问根 URL / 时,会调用 index 函数。

路由参数

您可以使用参数来使路由更加灵活。以下是一个带有参数的路由示例:

@app.route('/user/<username>')
def show_user_profile(username):
    return f'用户 {username} 的信息'

在这个例子中,<username> 是一个参数,它会替换为实际的用户名。

路由装饰器

Flask 使用装饰器来定义路由。以下是一些常用的路由装饰器:

  • @app.route():定义路由规则。
  • @app.get():定义一个只接受 GET 请求的路由。
  • @app.post():定义一个只接受 POST 请求的路由。

动态路由

动态路由允许您在 URL 中包含变量。以下是一个动态路由的示例:

@app.route('/items/<int:item_id>')
def get_item(item_id):
    return f'项目 {item_id} 的信息'

在这个例子中,<int:item_id> 是一个动态部分,它会匹配一个整数。

路由命名

您可以使用 @app.route() 装饰器的 name 参数来给路由命名。这有助于在模板中引用路由。

@app.route('/login', name='login')
def login():
    return '登录页面'

现在,您可以在模板中使用 url_for('login') 来生成登录页面的 URL。

图像示例

Flask 路由示例

更多信息,请访问我们的 Flask 教程

# Flask Routing Documentation

Flask routing is a key part of building web applications. It allows you to define URLs and corresponding handler functions. Below is some basic knowledge about Flask routing.

## Routing Rules

Flask uses routing rules to match URLs. Here is a simple routing example:

```python
@app.route('/')
def index():
    return 'Home page'

In this example, when visiting the root URL /, the index function is called.

Routing Parameters

You can use parameters to make routes more flexible. Here is an example of a route with parameters:

@app.route('/user/<username>')
def show_user_profile(username):
    return f'User {username}\'s information'

In this example, <username> is a parameter that will be replaced with the actual username.

Routing Decorators

Flask uses decorators to define routes. Here are some commonly used routing decorators:

  • @app.route(): Defines a routing rule.
  • @app.get(): Defines a route that only accepts GET requests.
  • @app.post(): Defines a route that only accepts POST requests.

Dynamic Routing

Dynamic routing allows you to include variables in URLs. Here is an example of dynamic routing:

@app.route('/items/<int:item_id>')
def get_item(item_id):
    return f'Item {item_id} information'

In this example, <int:item_id> is a dynamic part that will match an integer.

Route Naming

You can use the name parameter of the @app.route() decorator to name a route. This helps to reference routes in templates.

@app.route('/login', name='login')
def login():
    return 'Login page'

Now, you can use url_for('login') in templates to generate the URL for the login page.

Image Example

Flask Routing Sample

For more information, please visit our Flask Tutorial.