flask框架(六)——闪现(get_flashed_message)、请求扩展、中间件(了解)
message
-设置:flash('aaa')
-取值:get_flashed_message()
-假设在a页面操作出错,跳转到b页面,在b页面显示a页面的错误信息
1 如果要用flash就必须设置app.secret_key = 'asdfasdf'
2 特点:存了,你可以在任意一次请求中获取,但是一旦取了一次,就没有了。这里的一次指的是在同一个路径下请求一次
3 我们可以使用 flash('普通信息',category="info"),通过category对信息做分类
4get_flashed_messages(with_categories=True,category_filter=("error",)),设置with_categories以键值对的形式获取
设置category_filter=("error",)进行分类信息的过滤
代码示例
from flask import Flask,flash,get_flashed_messages app = Flask(__name__)
app.secret_key = 'asdfasdf' @app.route('/index1')
def index():
#(category="message", message))
flash('超时错误',category="error") #设置信息,分类为error
flash('普通信息',category="info") #设置信息,分类为info
return "ssdsdsdfsd" @app.route('/error')
def error():
data = get_flashed_messages(with_categories=True,category_filter=("error","info"))
data1 = get_flashed_messages(with_categories=True, category_filter=("error", "info"))
print("data1",data1)
print("data",data)
return "错误信息" if __name__ == '__main__':
app.run()
操作流程
请求index1路由,执行flash,设置信息,并且分类
请求error路由,执行get_flash_message。with_categories参数可写可不写,写了参数就是(类型,设置信息)格式。category_filter是设置显示的哪个分类信息
设置with_categories=True,结果打印格式

不设置with_categories=True,结果打印格式

请求扩展
1.before_request 在访问正式的视图函数之前做一些事情(比如可以基于它做用户登录)
注意:如果你在一个before中加入return返回值,就会终止代码运行,不会往下走了。
from flask import Flask,request,render_template
app = Flask(__name__) @app.before_request
def befor1():
print(request)
print("我是请求之前1") @app.before_request
def befor2():
print("我是请求之前2") @app.route('/index')
def index():
print("我是真的视图")
return render_template("index.html") if __name__ == '__main__':
app.run()
结果是从上往下运行

2.after_request (在每个请求之后绑定一个函数,类似于django中间件中的process_response)
from flask import Flask,request,render_template
app = Flask(__name__) @app.after_request
def after1(response):
print("我是请求之后1")
return response @app.after_request
def after2(response):
print("我是请求之后2")
return response @app.route('/index')
def index():
print("我是真的视图")
return render_template("index.html") if __name__ == '__main__':
app.run()
结果是从下往上运行
3.before_first_request (在请求之前运行,如果不重启,只会运行第一次)
from flask import Flask,render_template
app = Flask(__name__) @app.before_first_request
def before_first():
print("") @app.route('/index')
def index():
print("我是真的视图")
return render_template("index.html") if __name__ == '__main__':
# app.__call__
app.run()
4.teardown_request (在正式请求之后绑定一个函数,无论有没有异常都会执行,如果没有异常这个参数e就返回None,有就记录这个异常)
from flask import Flask,render_template
app = Flask(__name__) @app.teardown_request
def tear(e):
print('teardown_request')
print(e) #返回异常信息 @app.route('/index')
def index():
print("我是真的视图")
return render_template("index.html") if __name__ == '__main__':
# app.__call__
app.run()
5.errorhandler (路径不存在时404,服务器内部错误500)
@app.errorhandler(404)
def error_404(arg):
print(arg) #返回路径错误信息
return "404错误了" @app.errorhandler(500)
def error(arg):
print(arg) #返回服务器错误信息
return "500错误了"
6.template_global (标签)
@app.template_global()
def sb(a1, a2):
return a1 + a2 @app.route('/index')
def index():
print("我是真的视图")
return render_template("index.html")
html
{{sb(1,2)}}
7.template_filter (过滤器)
@app.template_filter()
def db(a1, a2, a3):
return a1 + a2 + a3 html
#{{ 1|db(2,3)}}
总结:
1 重点掌握before_request和after_request,
2 注意有多个的情况,执行顺序
3 before_request请求拦截后(也就是有return值),response所有都执行
中间件(了解)
from flask import Flask
app = Flask(__name__)
@app.route('/')
def index():
return 'Hello World!'
# 模拟中间件
class Md(object):
def __init__(self,old_wsgi_app):
self.old_wsgi_app = old_wsgi_app
def __call__(self, environ, start_response):
print('开始之前')
ret = self.old_wsgi_app(environ, start_response)
print('结束之后')
return ret
if __name__ == '__main__':
#1我们发现当执行app.run方法的时候,最终执行run_simple,最后执行app(),也就是在执行app.__call__方法
#2 在__call__里面,执行的是self.wsgi_app().那我们希望在执行他本身的wsgi之前做点事情。
#3 所以我们先用Md类中__init__,保存之前的wsgi,然后我们用将app.wsgi转化成Md的对象。
#4 那执行新的的app.wsgi_app,就是执行Md的__call__方法。
#把原来的wsgi_app替换为自定义的,
app.wsgi_app = Md(app.wsgi_app)
app.run()
请求所有的流程
ctx = self.request_context(environ)
error = None
try:
try:
ctx.push()
#根据路径去执行视图函数,视图类
response = self.full_dispatch_request()
except Exception as e:
error = e
response = self.handle_exception(e)
except: # noqa: B001
error = sys.exc_info()[1]
raise
return response(environ, start_response)
finally:
#不管出不出异常,都会走这里
if self.should_ignore_error(error):
error = None
ctx.auto_pop(error)
flask框架(六)——闪现(get_flashed_message)、请求扩展、中间件(了解)的更多相关文章
- Flask框架(三)—— 请求扩展、中间件、蓝图、session源码分析
Flask框架(三)—— 请求扩展.中间件.蓝图.session源码分析 目录 请求扩展.中间件.蓝图.session源码分析 一.请求扩展 1.before_request 2.after_requ ...
- Flask的闪现(message) 请求扩展 中间件 蓝图
补充:一个编程思路 需求:做一些邮件短信微信的消息通知,比如账单告警之类的:比如数据库操作,数据库种类繁多:缓存的选择比如redis/memcache,诸如此类需要进行选择配置,如果我们单纯的用函数去 ...
- Flask框架 (四)—— 请求上下文源码分析、g对象、第三方插件(flask_session、flask_script、wtforms)、信号
Flask框架 (四)—— 请求上下文源码分析.g对象.第三方插件(flask_session.flask_script.wtforms).信号 目录 请求上下文源码分析.g对象.第三方插件(flas ...
- Flask - 请求响应 | session | 闪现 | 请求扩展 | 中间件
请求响应 flask的请求信息都在request里 flask的响应方式有四剑客,也可以自定义响应 请求相关信息 # request.method 提交的方法 # request.args get请求 ...
- session、闪现、请求扩展
session 除请求对象之外,还有一个session对象.它允许你在不同请求储存特定用户的信息.它是在Cookies的基础上实现的,并且对,Cookies进行密钥签名要使用会话,你需要设置一个密钥. ...
- Flask框架 之上下文、请求钩子与Flask_Script
一.上下文 请求上下文:request与session 应用上下文:current_app与g:一次请求多个函数可以用它传参 @app.route("/") def index() ...
- flask 框架 前端和后端请求超时问题
部署模式 flask + Gunicorn + nginx 为什么要用Gunicorn + nginx ? 请看知乎大神们的回答:https://www.zhihu.com/question/3852 ...
- flask之请求与响应、闪现(阅后即焚)、请求扩展(before,after)、中间件、LOCAL对象、偏函数、
目录 1.flask请求与响应 2.闪现 3.请求扩展 4.中间件 5.LOCAL对象 6.偏函数 templates 1.flask请求与响应 from flask import Flask,req ...
- python flask框架详解
Flask是一个Python编写的Web 微框架,让我们可以使用Python语言快速实现一个网站或Web服务.本文参考自Flask官方文档, 英文不好的同学也可以参考中文文档 1.安装flask pi ...
- Flask基础(01)-->Flask框架介绍
什么是Flask? 说白了,Flask就是一种web框架 在python中常用的框架有 flask django tornado 什么又是web框架呢? 为什么要使用web框架呢? 增强扩展性和稳定 ...
随机推荐
- Greenplum常用的gp_toolkit & pg_catalog监控语句
gp_toolkit 说明 Greenplum数据库提供了一个名为gp_tooikit的管理schema,该schema下有关于查询系统目录,日志文件, 用户创建(databases,schema,t ...
- 【洛谷P5158】 【模板】多项式快速插值
卡常严重,可有采用如下优化方案: 1.预处理单位根 2.少取几次模 3.复制数组时用 memcpy 4.进行多项式乘法项数少的时候直接暴力乘 5.进行多项式多点求值时如果项数小于500的话直接秦九昭展 ...
- web 介绍
Web介绍: w3c:万维网联盟组织,用来制定web标准的机构(组织) web标准:制作网页遵循的规范 web准备规范的分类:结构标准.表现标准.行为标准. 结构:html.表示:css.行为:Jav ...
- 2019.12.09 Scanner类(用户输入数据----引用数据类型)
创建:数据类型 变量名 = new 数据类型(): 引用:变量名.方法名(): //导包import java.util.Scanner;class Demo01{ public st ...
- centos7中运行ifconfig提示-bash: ifconfig: command not found
centos7中运行ifconfig提示-bash: ifconfig: command not found 查看/sbin/下是否有ifconfig,若没有通过如下命令安装 sudo yum ins ...
- Python3菜鸟教程笔记
多行语句 同一行显示多条语句 Print 输出
- Fiddler如何查找登陆的可用cookie用于其他请求?方式一
测试过程中,如果你的请求权限是通过cookie响应而不是通过token获得,那么使用如下设置: 1.进入fiddler抓取: 2.jmeter中使用cookie 直接放进去就好了,一般浏览器cooki ...
- PHP 之循环创建文件夹
/** * 循环创建文件夹 * @param string $dir 需要创建的文件夹路径 * @param integer $mode 文件夹权限 * @return bool 返回创建是否成功 * ...
- 统一异常处理@ControllerAdvice
一.异常处理 有异常就必须处理,通常会在方法后面throws异常,或者是在方法内部进行try catch处理. 直接throws Exception 直接throws Exception,抛的异常太过 ...
- 用DLL方式封装MDI子窗体
用DLL方式封装MDI子窗体是一种常用的软件研发技术,他的长处: 研发人员能够负责某一个模块的编写包括(界面+逻辑),能够互不干扰,模块研发完成后,主程式统一调用. 易于程式升级,当程式升级时,不用编 ...