当前位置:网站首页>【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()。
边栏推荐
- Mlsys 2020 | fedprox: Federation optimization of heterogeneous networks
- Idea sets the default line break for global newly created files
- 【已解决】如何生成漂亮的静态文档说明页
- Introduction to robotics I. spatial transformation (1) posture, transformation
- MATLB | real time opportunity constrained decision making and its application in power system
- 电气数据|IEEE118(含风能太阳能)
- [solved] how to generate a beautiful static document description page
- 一圖看懂!為什麼學校教了你Coding但還是不會的原因...
- Leetcode skimming questions_ Verify palindrome string II
- [Yu Yue education] Liaoning Vocational College of Architecture Web server application development reference
猜你喜欢

1791. Find the central node of the star diagram / 1790 Can two strings be equal by performing string exchange only once

JVM_ 15_ Concepts related to garbage collection

XSS learning XSS lab problem solution

282. Stone consolidation (interval DP)

Who knows how to modify the data type accuracy of the columns in the database table of Damon
![[机缘参悟-39]:鬼谷子-第五飞箝篇 - 警示之二:赞美的六种类型,谨防享受赞美快感如同鱼儿享受诱饵。](/img/3c/ec97abfabecb3f0c821beb6cfe2983.jpg)
[机缘参悟-39]:鬼谷子-第五飞箝篇 - 警示之二:赞美的六种类型,谨防享受赞美快感如同鱼儿享受诱饵。
![[detailed] several ways to quickly realize object mapping](/img/e5/70c7f8fee4556d14f969fe33938971.gif)
[detailed] several ways to quickly realize object mapping

Idea sets the default line break for global newly created files

Leetcode skimming questions_ Verify palindrome string II

IP storage and query in MySQL
随机推荐
Remember that a version of @nestjs/typeorm^8.1.4 cannot be obtained Env option problem
Vulhub vulnerability recurrence 74_ Wordpress
c#网页打开winform exe
ThreeDPoseTracker项目解析
Unity VR resource flash surface in scene
After 95, the CV engineer posted the payroll and made up this. It's really fragrant
2020.2.13
3D vision - 4 Getting started with gesture recognition - using mediapipe includes single frame and real time video
Folio.ink 免费、快速、易用的图片分享工具
Blue Bridge Cup embedded stm32g431 - the real topic and code of the eighth provincial competition
现货白银的一般操作方法
Spir - V premier aperçu
JVM_ 15_ Concepts related to garbage collection
Is chaozhaojin safe? Will it lose its principal
Recursive method to realize the insertion operation in binary search tree
伦敦银走势中的假突破
Leetcode daily question solution: 1189 Maximum number of "balloons"
leetcode刷题_平方数之和
[day 30] given an integer n, find the sum of its factors
ctf. Show PHP feature (89~110)