session

除请求对象之外,还有一个session对象。它允许你在不同请求储存特定用户的信息。它是在Cookies的基础上实现的,并且对,Cookies进行密钥签名要使用会话,你需要设置一个密钥。

(app.session_interface对象)

使用必须先设置一下密钥:app.secret_key = 'xxxx'
session['name'] = 'xxx' #放值
session['name'] # 取值

源码执行流程

1.save_session -- 响应的时候,把session中的值加密序列化到cookie中,返回到浏览器中

2.open_session -- 请求来了,从cookie中取值,反解生成session对象,以后再视图函数中直接用session就可以了

闪现(message)

#设置值
flash('我错了')
flash('超时错误',category='x1')
#取值:一旦取过一次,在另一个函数中再取就没了
get_flashed_messages()
get_flashed_messages(category_filter=['x1','x2'])
#使用场景:在某个位置放一个值,过来去取出来
from flask import Flask, get_flashed_messages, flash, url_for

app = Flask(__name__)
app.secret_key = 'xxxxadadad' @app.route('/', methods=['GET', 'POST'])
def index():
# error='我出错了'
# url=url_for('test')
# url=url+'?error=%s'%error
# 使用flash实现,相当于在某个位置放了值
flash('我出错了', category='xxx')
url = url_for('test')
# return redirect(url)
return 'ok' @app.route('/test/', methods=['GET', 'POST'])
def test():
# error=request.args.get('error')
# print(error)
# 使用闪现
# 从某个位置取出来值
error = get_flashed_messages(category_filter=['xxx'])
print(error)
return 'ok' @app.route('/test2/', methods=['GET', 'POST'])
def test2():
# error=get_flashed_messages()
# print(error)
flash('我出错了')
return 'test2' if __name__ == '__main__':
app.run()

请求扩展

before_request

类比Django中间件中的process_request,在请求收到之前绑定一个函数做一些事情

@app.before_request
def before_request():
print('来了')
after_request

类比Django中间件中的process_response,每一个请求之后绑定一个函数,如果请求没有异常

@app.after_request
def after_request(response):
print(type(response))
print('走了了')
return response
before_first_request(服务一启动,第一次请求会走,以后再也不走了)
@app.before_first_request
def first():
print('我的第一次')
teardown_request

无论如何都会走,即便出了异常

@app.teardown_request
def ter(e):
print(e)
print('无论如何都会走,即便出了异常')
errorhandler

路径存在时404,服务器内部错误500

@app.errorhandler(404)
def error_404(arg):
# return render_template('')
return '你迷路了'
template_global

标签

@app.template_global()
def sb(a1, a2):
return a1 + a2
#{{sb(1,2)}}
template_filter

过滤器

@app.template_filter()
def db(a1, a2, a3):
return a1 + a2 + a3
#{{ 1|db(2,3)}}

总结:

注意有多个的情况,执行顺序(before_request按照顺序往下依次执行,after_request最后一个开始依次往上)。before_request请求拦截后(也就是有return值),response所有都执行。

最新文章

  1. RecyclerView局部刷新那点事
  2. Laravel教程 一:安装及环境配置
  3. Mongodb数据操作基础
  4. MySQL通过Binlog恢复删除的表
  5. 20160730noip模拟赛zld
  6. 如何把jquery 的dialog和ztree结合
  7. Going Home(最小费用最大流)
  8. GIT 实验
  9. Web用户控件
  10. dom4j解析xml实例(2)
  11. 正则表达式获取body内容
  12. Linux shell查询ip归属地
  13. iOS开源加密相册Agony的实现(一)
  14. jquery选择器 看这个链接吧!2017.6.2
  15. 浅谈Web开发中的定时任务
  16. .Net Core 管道中的ConfigureServices 和Configure
  17. Python爬虫学习--用Python结合Selenium实现 明日之子节目直播时为自己喜欢的选手自动点赞拉票!!!
  18. mysql配置优化浅谈(一)
  19. Java 时间总结
  20. 语句调优基础知识-set statistics io on

热门文章

  1. C++置换的玩笑
  2. 使用BurpSuite、Hydra和medusa爆破相关的服务
  3. 笔记:Xshell、更新源、安装软件
  4. idea生成SpringBoot项目后再次调出依赖
  5. echarts 导出为word文档
  6. Hive中的用户自定义函数
  7. 为什么 java.util.Stack不被官方所推荐使用!
  8. webpack 热替换
  9. 【Spring】Spring如何实现多数据源读写分离?这是我看过最详细的一篇!!
  10. 通过自定义资源扩展Kubernetes