请求钩子
在客户端和服务器交互的过程中,有些准备工作或扫尾工作需要处理,比如:在请求开始时,建立数据库连接;在请求结束时,指定数据的交互格式。为了让每个视图函数避免编写重复功能的代码,Flask提供了通用设施的功能,即请求钩子。
请求钩子是通过装饰器的形式实现,Flask支持如下四种请求钩子:
before_first_request:在处理第一个请求前运行。
before_request:在每次请求前运行。
after_request:如果没有未处理的异常抛出,在每次请求后运行。
teardown_request:在每次请求后运行,即使有未处理的异常抛出。
请求钩子是通过装饰器的形式实现,Flask支持如下四种请求钩子:
# coding:utf-8 from flask import Flask, session, current_app, request, url_for app = Flask(__name__) @app.route("/index") def index(): print("index 被执行") # a = 1 / 0 模拟出错 return "index page" @app.route("/hello") def hello(): print("hello 被执行") return "hello page" @app.before_first_request def handle_before_first_request(): """在第一次请求处理之前先被执行""" print("handle_before_first_request 被执行") @app.before_request def handle_before_request(): """在每次请求之前都被执行""" print("handle_before_request 被执行") @app.after_request def handle_after_request(response): """在每次请求(视图函数处理)之后都被执行, 前提是视图函数没有出现异常""" print("handle_after_request 被执行") return response @app.teardown_request def handle_teardown_request(response): """在每次请求 (视图函数处理)之后都被执行, 无论视图函数是否出现异常,都被执行, 工作在非调试模式时 debug=False""" path = request.path # print(path) if path == url_for("index"): print("在请求钩子中判断请求的视图逻辑: index") elif path == url_for("hello"): print("在请求钩子中判断请求的视图逻辑: hello") print("handle_teardown_request 被执行") return response if __name__ == '__main__': app.run()
flask的上下文对象
请求上下文(request context)
request和session都属于请求上下文对象。
应用上下文(application context)
current_app和g都属于应用上下文对象。
current_app:表示当前运行程序文件的程序实例。
g:处理请求时,用于临时存储的对象,每次请求都会重设这个变量。 一次请求执行的多个函数之间传递变量 应用:用户登录后,保存用户的用户名等信息,其他函数想要用的时候直接拿
django中的request 是局部变量,具体的请求信息
flask 中的request 是全局变量,里面维护了一个字典记录着不同请求的信息(利用线程局部变量实现,每个请求根据自己的线程编号去取对应的变量)。上下文即每个请求自己所属的环境,跟具体的用户请求有关。
flask_script脚本扩展的使用
通过使用Flask-Script扩展,我们可以在Flask服务器启动的时候,通过命令行的方式传入参数。而不仅仅通过app.run()方法中传参,比如我们可以通过python hello.py runserver --host ip地址,告诉服务器在哪个网络接口监听来自客户端的连接。默认情况下,服务器只监听来自服务器所在计算机发起的连接,即localhost连接。
我们可以通过python hello.py runserver --help来查看参数。
# coding:utf-8 from flask import Flask from flask_script import Manager # 启动命令的管理类 app = Flask(__name__) # 创建Manager管理类的对象 manager = Manager(app) @app.route("/index") def index(): return "index page" if __name__ == '__main__': # app.run(debug=True) # 通过管理对象来启动flask manager.run()