Flask的路由和视图函数

来源:互联网 发布:python exit status 2 编辑:程序博客网 时间:2024/06/10 03:36

Flask的路由和视图函数

在Flask定义路由的最简便方式,是使用程序实例提供的app。route修饰器,把修饰的函数注册为路由

如:

@app.route('/')def index():    return 'Index Page'@app.route('/hello')def hello():    return 'Hello World'

像index这样的函数为视图函数

不仅如此!你可以构造含有动态部分的 URL,也可以在一个函数上附着多个规则。

变量规则

要给 URL 添加变量部分,你可以把这些特殊的字段标记为 <variable_name> , 这个部分将会作为命名参数传递到你的函数。规则可以用 <converter:variable_name> 指定一个可选的转换器。这里有一些不错的例子:

@app.route('/user/<username>')def show_user_profile(username):    # show the user profile for that user    return 'User %s' % username@app.route('/post/<int:post_id>')def show_post(post_id):    # show the post with the given id, the id is an integer    return 'Post %d' % post_id    ```## 程序请求上下文### Flask从客户端收到请求,需让视图函数能访问一些对象,才能处理请求。为了避免大量可有可无的参数把视图函数弄的一团糟,Flask使用上下文把某些对象变为全局可访问。### 如:```Pythonfrom Flask import request@app.route('/')def index():    user=request.headers.get('User-Agent')    return 'your browser is %s' % user

HTTP 方法

HTTP (与 Web 应用会话的协议)有许多不同的访问 URL 方法。默认情况下,路由只回应 GET 请求,但是通过 route() 装饰器传递 methods 参数可以改变这个行为。这里有一些例子:

@app.route('/login', methods=['GET', 'POST'])def login():    if request.method == 'POST':        do_the_login()    else:        show_the_login_form()

模板渲染

用 Python 生成 HTML 十分无趣,而且相当繁琐,因为你必须手动对 HTML 做转义来保证应用的安全。为此,Flask 配备了 Jinja2 模板引擎。

你可以使用 render_template() 方法来渲染模板。你需要做的一切就是将模板名和你想作为关键字的参数传入模板的变量。这里有一个展示如何渲染模板的简例:

from flask import render_template@app.route('/hello/')@app.route('/hello/<name>')def hello(name=None):    return render_template('hello.html', name=name)
原创粉丝点击