flask --- Cookies和session
<原文网址:https://dormousehole.readthedocs.io/en/latest/quickstart.html#cookies>
1. Cookies:
要访问 cookies ,可以使用 cookies 属性。可以使用响应 对象 的 set_cookie 方法来设置 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
2. session
<session: https://dormousehole.readthedocs.io/en/latest/quickstart.html#sessions>
除了请求对象之外还有一种称为 session 的对象,允许您在不同请求 之间储存信息。这个对象相当于用密钥签名加密的 cookie ,即用户可以查看您的 cookie ,但是如果没有密钥就无法修改它。
使用会话之前您必须设置一个密钥。举例说明:
from flask import session # Set the secret key to some random bytes. Keep this really secret! app.secret_key = b'_5#y2L"F4Q8z\n\xec]/' @app.route('/') def index(): if 'username' in session: return f'Logged in as {session["username"]}' #取出session中用户名 return 'You are not logged in' @app.route('/login', methods=['GET', 'POST']) def login(): if request.method == 'POST': session['username'] = request.form['username'] #把用户名存session中 return redirect(url_for('index')) return ''' <form method="post"> <p><input type=text name=username> <p><input type=submit value=Login> </form> ''' @app.route('/logout') def logout(): # remove the username from the session if it's there session.pop('username', None) #删除session中的用户名 return redirect(url_for('index'))
如何生成一个好的密钥 生成随机数的关键在于一个好的随机种子,因此一个好的密钥应当有足够的随机性。 操作系统可以有多种方式基于密码随机生成器来生成随机数据。使用下面的命令
可以快捷的为 Flask.secret_key ( 或者 SECRET_KEY )生成值: $ python -c 'import os; print(os.urandom(16))' b'_5#y2L"F4Q8z\n\xec]/'

浙公网安备 33010602011771号