加载app程序运行参数
app.config表示app程序,运行所有的参数信息
-
从配置类(对象)中加载
app.config.from_object(obj)
-
从配置文件中加载
app.config.from_pyfile(file)
-
从环境变量中加载(不常用,如有特殊需要建议百度)
app.config.from_envvar(环境变量)
示例:
from pprint import pprint
from flask import Flask
app = Flask(__name__)
# pprint(app.config)
# 1.从配置类(对象)中加载
class MyConfig(object):
# 调试模式
DEBUG = True
# app.config.from_object(MyConfig)
# 2.从配置文件中加载
app.config.from_pyfile("Config.ini")
@app.route('/')
def hello_world():
return "hello world"
if __name__ == '__main__':
app.run()
请求钩子
-
解释:当访问正常视图函数的时候,顺带执行的方法
-
常见的请求钩子有四种:
1.before_first_request:在处理第一个请求前执行 2.before_request:在每次请求前执行,在该装饰函数中,一旦return,视图函数不再执行 3.after_request:如果没有抛出错误,在每次请求后执行 接收一个参数:视图函数做出的响应 在此函数中可以对响应值,在返回之前做最后一步处理,再返回 4.teardown_request:在每次请求后执行 接收一个参数:用来接收错误信息
示例:
from flask import Flask
app = Flask(__name__)
# before_first_request装饰的函数在第一次访问的时候执行,里面适合做初始化操作,比如,io文件读写
@app.before_first_request
def before_first_request():
print("before_first_request")
# before_request,每次请求前都执行,适合对请求参数做校验,访问统计
@app.before_request
def before_request():
print("before_request")
# after_request,视图函数执行之后,返回该方法,适合对返回值做统一处理,比如:返回统一的json数据格式
@app.after_request
def after_request(resp):
print("after_request")
resp.headers["Content-Type"] = "application/json"
return resp
# teardown_request,请求销毁之后,执行该方法,适合做异常信息统计
@app.teardown_request
def teardown_request(e):
print(e)
print("teardown_request")
@app.route('/')
def hello_world():
return "hello world"
if __name__ == '__main__':
app.run(debug=True)