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

相關文章
相關標籤/搜索