zoukankan      html  css  js  c++  java
  • 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

    添加启动脚本Manager

    # 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来查看帮助信息

    (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这个模块就可以直接是用它

  • 相关阅读:
    python zip,lambda,map函数
    TKinter Scale
    TKinter Radiobutton
    TKinter Listbox
    TKinter Entry 和 Text
    TKinter Label 和 Button
    python中global的用法
    收不到github认证邮件
    IDEA中文显示字体混乱
    使用码云加速下载github项目
  • 原文地址:https://www.cnblogs.com/Hannibal-2018/p/11240670.html
Copyright © 2011-2022 走看看