一、上下文
- 请求上下文:request与session
- 应用上下文:current_app与g:一次请求多个函数可以用它传参
@app.route("/")
def index():
g.username = "yy"
test()
return "page" # 1、请求上下文:request与session
# 2、应用上下文:current_app与g:一次请求多个函数可以用它传参
def test():
print(g.username)
二、请求钩子
请求钩子是通过装饰器实现的,flask有四种钩子(hook):
- before_first_request:在处理第一个请求前运行
- before_request:在每次请求前运行
- after_request(Response):如果没有未处理的异常抛出,每次请求后执行
- teardown_request(Response):在每次请求后执行,即使有异常抛出
@app.route("/")
def index():
return "page" @app.route("/login")
def login():
return "login" @app.before_first_request
def first():
print("before_first_request") @app.before_request
def check_login():
do_url = request.path
if do_url != "/login":
return redirect(url_for("login")) @app.after_request
def after(response):
print("after_request")
return response @app.teardown_request
def teardown(response):
print("teardown_request")
return response
三、Flask_Script扩展
安装:pip install flask_script
from flask import Flask
from flask_script import Manager app = Flask(__name__)
manager = Manager(app) @app.route("/")
def index():
return "index page" if __name__ == '__main__':
manager.run()
执行方式:python flask_script扩展.py runserver -p 8013
参数说明如下:
-?, --help show this help message and exit
-h HOST, --host HOST
-p PORT, --port PORT
--threaded
--processes PROCESSES
--passthrough-errors
-d, --debug enable the Werkzeug debugger (DO NOT use in production
code)
-D, --no-debug disable the Werkzeug debugger
-r, --reload monitor Python files for changes (not 100% safe for
production use)
-R, --no-reload do not monitor Python files for changes
--ssl-crt SSL_CRT Path to ssl certificate
--ssl-key SSL_KEY Path to ssl key