笨鸟编程-零基础入门Pyhton教程

 找回密码
 立即注册

快速入门

发布者: 笨鸟自学网



Cookies

你可以通过 cookies 属性来访问 Cookies,用 响应对象的 set_cookie 方法来设置 Cookies。请 求对象的 cookies 属性是一个内容为客户端提交的 所有 Cookies 的字典。如果你想使用会话,请不要直接使用 Cookies,请参 考 会话 一节。在 Flask 中,已经注意处理了一些 Cookies 安全 细节。

读取 cookies:

from flask import request

@app.route('/')
def index():
    username = request.cookies.get('username')
    # use cookies.get(key) instead of cookies[key] to not get a
    # KeyError if the cookie is missing.

存储 cookies:

from flask import make_response

@app.route('/')
def index():
    resp = make_response(render_template(...))
    resp.set_cookie('username', 'the username')
    return resp

可注意到的是,Cookies 是设置在响应对象上的。由于通常视图函数只是返 回字符串,之后 Flask 将字符串转换为响应对象。如果你要显式地转换,你 可以使用 make_response() 函数然后再进行修改。

有时候你想设置 Cookie,但响应对象不能醋在。这可以利用 延迟请求回调 模式实现。

为此,也可以阅读 关于响应 。

重定向和错误

你可以用 redirect() 函数把用户重定向到其它地方。放弃请 求并返回错误代码,用 abort() 函数。这里是一个它们如何 使用的例子:

from flask import abort, redirect, url_for

@app.route('/')
def index():
    return redirect(url_for('login'))

@app.route('/login')
def login():
    abort(401)
    this_is_never_executed()

这是一个相当无意义的例子因为用户会从主页重定向到一个不能访问的页面 (401 意味着禁止访问),但是它展示了重定向是如何工作的。

默认情况下,错误代码会显示一个黑白的错误页面。如果你要定制错误页面, 可以使用 errorhandler() 装饰器:

from flask import render_template

@app.errorhandler(404)
def page_not_found(error):
    return render_template('page_not_found.html'), 404

注意 render_template() 调用之后的 404 。这告诉 Flask,该页的错误代码是 404 ,即没有找到。默认为 200,也就是一切 正常。

关于响应

视图函数的返回值会被自动转换为一个响应对象。如果返回值是一个字符串, 它被转换为该字符串为主体的、状态码为 200 OK``的  MIME 类型是 ``text/html 的响应对象。Flask 把返回值转换为响应对象的逻辑是这样:

  1. 如果返回的是一个合法的响应对象,它会从视图直接返回。
  2. 如果返回的是一个字符串,响应对象会用字符串数据和默认参数创建。
  3. 如果返回的是一个元组,且元组中的元素可以提供额外的信息。这样的 元组必须是 (response, status, headers) 的形式,且至少包含一 个元素。 status 值会覆盖状态代码, headers 可以是一个列表或 字典,作为额外的消息标头值。
  4. 如果上述条件均不满足, Flask 会假设返回值是一个合法的 WSGI 应用 程序,并转换为一个请求对象。

如果你想在视图里操纵上述步骤结果的响应对象,可以使用 make_response() 函数。

譬如你有这样一个视图:

@app.errorhandler(404)
def not_found(error):
    return render_template('error.html'), 404

你只需要把返回值表达式传递给 make_response() ,获取结 果对象并修改,然后再返回它:

@app.errorhandler(404)
def not_found(error):
    resp = make_response(render_template('error.html'), 404)
    resp.headers['X-Something'] = 'A value'
    return resp 

上一篇:安装下一篇:介绍 Flaskr

Archiver|手机版|笨鸟自学网 ( 粤ICP备20019910号 )

GMT+8, 2024-9-8 11:38 , Processed in 0.070870 second(s), 17 queries .

© 2001-2020

返回顶部