Flask 简明教程

Flask – Routing

现代网络框架使用路由技术来帮助用户记住应用程序 URL。这对于直接访问目标页面非常有用,而无需从主页进行导航。

Modern web frameworks use the routing technique to help a user remember application URLs. It is useful to access the desired page directly without having to navigate from the home page.

Flask 中的 route() 装饰器用于将 URL 与一个函数进行绑定。例如 −

The route() decorator in Flask is used to bind URL to a function. For example −

@app.route(‘/hello’)
def hello_world():
   return ‘hello world’

在这里,URL ‘/hello’ 规则被绑定至 hello_world() 函数。因此,如果用户访问 http://localhost:5000/hello URL, hello_world() 函数的输出数据将在浏览器中渲染出来。

Here, URL ‘/hello’ rule is bound to the hello_world() function. As a result, if a user visits http://localhost:5000/hello URL, the output of the hello_world() function will be rendered in the browser.

某个应用程序对象中的 add_url_rule() 函数还可以用于将 URL 与函数进行绑定,如同在上述示例中使用 route() 的情况。

The add_url_rule() function of an application object is also available to bind a URL with a function as in the above example, route() is used.

以下表示法也可以实现装饰器的目的 −

A decorator’s purpose is also served by the following representation −

def hello_world():
   return ‘hello world’
app.add_url_rule(‘/’, ‘hello’, hello_world)