在shall中runserver 命令行没有输出_17. FlaskScript扩展命令行

介绍

在Django中启动服务的时候,可以使用python manage.py runserver 或者 python manage.py shell,那么Flask能否也执行该类的扩展命令行呢?

下面来看看。

Flask-Script扩展

Flask-Script 的引入以及使用:

# 安装flask_script
pip3 install flask_script

# 引入flask_script
from flask_script import Manager # 启动命令的管理类

# 创建flask的app应用对象
app = Flask(__name__)

# 创建Manager管理类的对象
manager = Manager(app)

# 通过管理对象来启动flask
manager.run()

通过使用Flask-Script扩展,我们可以在Flask服务器启动的时候,通过命令行的方式传入参数。

完整示例代码

from flask import Flask
from flask_script import Manager # 启动命令的管理类

# 创建Flask的app应用
app = Flask(__name__)

# 创建Manager管理类的对象
manager = Manager(app)

# index视图函数
@app.route("/index")
def index():
return "index page"

if __name__ == '__main__':
# app.run(debug=True)
# 通过管理对象来启动flask
manager.run()

使用命令行启动flask

启动Flask应用不仅仅可以通过app.run()方法中传参以及启动,通过flask_script可以通过python hello.py runserver 来启动服务,如下:

78c3c0d8309a984392ad172c2cb0ccb4.png

指定IP和端口号命令行启动flask

还可以指定IP和端口号的启动方式,如下:

$ python3 09_flask_script.py runserver --help
usage: 09_flask_script.py runserver [-?] [-h HOST] [-p PORT] [--threaded]
[--processes PROCESSES]
[--passthrough-errors] [-d] [-D] [-r] [-R]
[--ssl-crt SSL_CRT] [--ssl-key SSL_KEY]

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% 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
4bcbe070ee2a189771296227c77ed052.png

我们还可以通过--help来查看参数。

e0e9a685a83c27976f161a26b68b6502.png

默认可以看到命令行只可以使用shellrunserver

执行flask的交互shell模式

最后再来看看启动交互式的shell,如下:

$ python3 09_flask_script.py shell

# 导入当前的应用
In [1]: from flask import current_app

# 打印当前应用的名称
In [2]: current_app.name
Out[2]: '09_flask_script'

# 不需要导入app了,默认就可以直接使用脚本已经定义好的方法以及对象
In [3]: app.url_map
Out[3]:
Map(['/index' (GET, OPTIONS, HEAD) -> index>,'/static/' (GET, OPTIONS, HEAD) -> static>])
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值