Flask-1-06-script扩展

在学习扩展以前,先介绍几个概念,本身的思路还不是很清晰,因此暂时还没办法作过多的讲解

请求上下文与应用上下文

请求上下文 (request context)

  • request

  • session

应用上下文(application context)

  • current_app

  • g (处理请求时,用于临时存储的对象,每次请求都会重设这个变量)

请求钩子

请求钩子是经过装饰器的形式实现,Flask支持以下四种请求钩子:

 

  • before_first_request:在处理第一个请求前运行。 @app.before_first_request

 

  • before_request:在每次请求前运行。 @app.before_request

 

  • after_request(response):若是没有未处理的异常抛出,在每次请求后运行。 @app.after_request

 

  • teardown_request(response):在每次请求后运行,即便有未处理的异常抛出。 @app.teardown_request 注释:须要在生产模式下,也就是debug=False的时候

简单的示例:

 

# coding:utf-8

from flask import Flask

app = Flask(__name__)


@app.route("/index")
def index():
    print("index 执行了")
    return 'index page'


@app.before_first_request
def before_first_request_function():
    """在第一次请求处理以前先被执行"""
    print("before first request function 执行了")


@app.before_request
def before_request_function():
    """在每次请求以前都被执行"""
    print("before request function 执行了")


@app.after_request
def after_request_function(response):
    """在每次请求(视图函数处理)以后都被执行, 前提是视图函数没有出现异常"""
    print("after request function 执行了")
    return response


@app.teardown_request
def teardown_request_function(response):
    """在每次请求 (视图函数处理)以后都被执行, 不管视图函数是否出现异常,都被执行, 工做在非调试模式时 debug=False"""
    print("teardown request function 执行了")


if __name__ == '__main__':
    app.run(host='0.0.0.0')

 

# 展现结果
(Flask_py) python@python-VirtualBox:~/code$ python hook_demo.py 
 * Running on http://0.0.0.0:5000/ (Press CTRL+C to quit)
before first request function 执行了
before request function 执行了
index 执行了
after request function 执行了
teardown request function 执行了
127.0.0.1 - - [24/Jul/2019 19:39:20] "GET /index HTTP/1.1" 200 -

 

 

Flask-Script 扩展脚本


 

安装

pip install Flask-Script

添加启动脚本Managerpython

# 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()

在终端启动以前咱们能够经过help查看帮助信息

(Flask_py) python@python-VirtualBox:~/code$ python flask_scirpt_demo.py --help
usage: flask_scirpt_demo.py [-?] {shell,runserver} ...

positional arguments:
  {shell,runserver}
    shell            Runs a Python shell inside Flask application context.
    runserver        Runs the Flask development server i.e. app.run()

optional arguments:
  -?, --help         show this help message and exit

能够看出有两个命令可供咱们选择,选定runserver再次经过help来查看帮助信息shell

(Flask_py) python@python-VirtualBox:~/code$ python flask_scirpt_demo.py runserver --help
usage: flask_scirpt_demo.py runserver [-?] [-h HOST] [-p PORT] [--threaded]
                                      [--processes PROCESSES]
                                      [--passthrough-errors] [-d] [-D] [-r]
                                      [-R]

Runs the Flask development server i.e. app.run()

optional arguments:
  -?, --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{'const':
                        True, 'help': 'monitor Python files for changes (not
                        100% safe for production use)', 'option_strings':
                        ['-r', '--reload'], 'dest': 'use_reloader',
                        'required': False, 'nargs': 0, 'choices': None,
                        'default': None, 'prog': 'flask_scirpt_demo.py
                        runserver', 'container': <argparse._ArgumentGroup
                        object at 0x7f2a3e8db290>, 'type': None, 'metavar':
                        None}afe for production use)
  -R, --no-reload       do not monitor Python files for changes

启动而且指定 host:0.0.0.0 port :12345  而且经过本地ip或者127.0.0.1访问 

(Flask_py) python@python-VirtualBox:~/code$ python flask_scirpt_demo.py runserver -h 0.0.0.0 -p 12345
 * Running on http://0.0.0.0:12345/ (Press CTRL+C to quit)
127.0.0.1 - - [24/Jul/2019 20:00:43] "GET /index HTTP/1.1" 200 -
127.0.0.1 - - [24/Jul/2019 20:00:43] "GET /favicon.ico HTTP/1.1" 404 -

 展现结果:

除了runserver这个选项还有一个就是shell这个选项

就是进入了ipython这个编译器在这里你不须要导入flask_script_demo这个模块就能够直接是用它flask

相关文章
相关标签/搜索