当前位置:网站首页>【Flask】响应、session与Message Flashing
【Flask】响应、session与Message Flashing
2022-07-06 01:26:00 【科皮子菊】
前序文章:
响应Response
视图函数(请求处理对应的函数)的返回值会自动为您转换为响应对象。如果返回值是一个字符串,它会被转换成一个响应对象,其中字符串作为响应主体,一个 200 OK 状态码和一个 text/html mimetype。如果返回值是一个dict类型的数据,我们则需要借用jsonify()
去生成一个response。Flask 应用于将返回值转换为响应对象的逻辑如下:
- 如果返回正确类型的响应对象,则直接从视图返回。
- 如果它是一个字符串,则使用该数据和默认参数创建一个响应对象。
- 如果是 dict,则使用
jsonify
创建一个响应对象。 - 如果返回元组,则元组中的项目可以提供额外信息。此类元组必须采用 (response, status)、(response, headers) 或 (response, status, headers) 的形式。
status
将覆盖状态代码,并且headers
可以是附加标头值的列表或字典。 - 如果这些都不起作用,Flask 将假定返回值是有效的 WSGI 应用程序并将其转换为响应对象。
如果要在视图中获取结果响应对象,可以使用 make_response()
函数。
假如我们有如下的视图:
from flask import render_template
@app.errorhandler(404)
def not_found(error):
return render_template('error.html'), 404
你只需要用 make_response()
包装返回表达式并获取响应对象来修改它,然后返回它:
from flask import 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
JSON类型的API
在前后分离的开发中,数据的交互方式大多都是使用json格式的数据作为媒介。使用 Flask 很容易开始编写这样的 API。如果您从视图返回 dict,它将被转换为 JSON 响应。
@app.route("/me")
def me_api():
user = get_current_user()
return {
"username": user.username,
"theme": user.theme,
"image": url_for("user_image", filename=user.image),
}
根据您的 API 设计,您可能希望为 dict 以外的类型创建 JSON 响应。在这种情况下,使用jsonify()
函数,它将序列化任何支持的 JSON 数据类型。或者查看支持更复杂应用程序的 Flask 社区扩展。
from flask import jsonify
@app.route("/users")
def users_api():
users = get_all_users()
return jsonify([user.to_json() for user in users])
session
除了请求对象之外,还有一个名为 session 的对象,它允许您存储从一个请求到下一个请求的特定于用户的信息。这是在 cookie 之上为您实现的,并以加密方式对 cookie 进行签名。这意味着用户可以查看您的 cookie 的内容但不能修改它,除非他们知道用于签名的密钥。
为了使用session,您必须设置一个密钥。以下是会话的工作方式:
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"]}'
return 'You are not logged in'
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
session['username'] = request.form['username']
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)
return redirect(url_for('index'))
如何生成好的密钥:密钥应尽可能随机。您的操作系统有办法基于加密随机生成器生成相当随机的数据。使用以下命令快速生成 Flask.secret_key(或 SECRET_KEY)的值:
python -c 'import secrets; print(secrets.token_hex())'
# '192b9bdd22ab9ed4d12e236c78afcb9a393ec15f71bbf5dc987d54727823bcbf'
关于基于 cookie 的会话的说明:Flask 将获取您放入会话对象的值并将它们序列化为 cookie。如果您发现某些值不会在请求中持续存在,则确实启用了 cookie,并且您没有收到明确的错误消息,请检查页面响应中 cookie 的大小与 Web 浏览器支持的大小相比。
除了默认的基于客户端的会话,如果你想在服务器端处理会话,有几个 Flask 扩展支持这个。
Message Flashing
好的应用程序和用户界面都是关于反馈的。如果用户没有得到足够的反馈,他们可能最终会讨厌该应用程序。Flask 提供了一种非常简单的方法,可以通过闪烁系统向用户提供反馈。闪烁系统基本上可以在请求结束时记录消息并在下一个(并且仅是下一个)请求时访问它。这通常与布局模板结合以公开消息。
要闪烁消息,请使用flash()
方法,要获取消息,您可以使用模板中也提供的 get_flashed_messages()
。
边栏推荐
- GNSS terminology
- Vulhub vulnerability recurrence 74_ Wordpress
- Leetcode 208. 实现 Trie (前缀树)
- SPIR-V初窥
- Recursive method converts ordered array into binary search tree
- General operation method of spot Silver
- Live broadcast system code, custom soft keyboard style: three kinds of switching: letters, numbers and punctuation
- ORA-00030
- 基於DVWA的文件上傳漏洞測試
- SPIR-V初窺
猜你喜欢
yii中console方法调用,yii console定时任务
3D视觉——4.手势识别(Gesture Recognition)入门——使用MediaPipe含单帧(Singel Frame)和实时视频(Real-Time Video)
JVM_ 15_ Concepts related to garbage collection
现货白银的一般操作方法
MySQL learning notes 2
Vulhub vulnerability recurrence 75_ XStream
DOM introduction
MUX VLAN configuration
282. Stone consolidation (interval DP)
[understanding of opportunity-39]: Guiguzi - Chapter 5 flying clamp - warning 2: there are six types of praise. Be careful to enjoy praise as fish enjoy bait.
随机推荐
Huawei Hrbrid interface and VLAN division based on IP
Leetcode daily question solution: 1189 Maximum number of "balloons"
[detailed] several ways to quickly realize object mapping
ThreeDPoseTracker项目解析
电气数据|IEEE118(含风能太阳能)
Differences between standard library functions and operators
Leetcode 剑指 Offer 59 - II. 队列的最大值
SPIR-V初窥
Gartner released the prediction of eight major network security trends from 2022 to 2023. Zero trust is the starting point and regulations cover a wider range
Dede collection plug-in free collection release push plug-in
Is chaozhaojin safe? Will it lose its principal
晶振是如何起振的?
Unity VR solves the problem that the handle ray keeps flashing after touching the button of the UI
SSH login is stuck and disconnected
DOM introduction
How to get the PHP version- How to get the PHP Version?
普通人下场全球贸易,新一轮结构性机会浮出水面
Building core knowledge points
【第30天】给定一个整数 n ,求它的因数之和
基於DVWA的文件上傳漏洞測試