flask-script模块简单使用介绍

flask-script

Flask每次启动只能在脚本中作为参数传给app.run()函数,比如我要启动端口为8000,那就需要在代码中或者配置文件中修改,很不方便。
Flask-Scrip就是这么一个Flask扩展,为Flask程序添加一个命令行解析器,可以使用命令行进行启动参数传递。

  • 安装

pip install flask-script

  • 继承flask-script到flask应用中
    保存下面代码为manager.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
from flask import Flask
from flask_script import Manager

app = Flask(__name__)
manager = Manager(app=app)


@app.route('/')
def index():
    return 'Hello, world~!'


if __name__ == '__main__':
    manager.run()
  • 自定义启动方式
    • cmd命令行下查看启动命令帮助
      在cmd命令行中,进入manager.py所在的路径,执行如下命令查看帮助(或者进入对应目录,在对应路径中输入cmd,即可打开当前路径的命令行模式…)
      在这里插入图片描述
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    python manager.py runserver --help
        -?, --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
  • 启动样例
1
2
3
4
5
6
7
8
9
10
C:\Users\Admin\Desktop\markdown>python manager.py runserver -h 0.0.0.0 -p 8000 -d -r
 * Serving Flask app "manager" (lazy loading)
 * Environment: production
   WARNING: This is a development server. Do not use it in a production deployment.
   Use a production WSGI server instead.
 * Debug mode: on
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 137-965-202
 * Running on http://0.0.0.0:8000/ (Press CTRL+C to quit)