遇见Flask-Script
Posted endurance9
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了遇见Flask-Script相关的知识,希望对你有一定的参考价值。
Flask-Script是Flask的命令行扩展包,使用它可以通过命令行的形式操作Flask项目, 例如,可通过命令启动一个发版本的服务器,设置数据库和定时任务等。
类似Django的manage.py提供的命令,不同的是使用flask-script可以自定义更多的命令。
Install flask-script
一般在虚拟环境中安装
(flask_env) [email protected]:~/PycharmProjects/flask_one$ pip install flask-script
Collecting flask-script
Downloading https://files.pythonhosted.org/packages/00/a4/cd587b2b19f043b65bf33ceda2f6e4e6cdbd0ce18d01a52b9559781b1da6/Flask-Script-2.0.6.tar.gz (43kB)
100% |████████████████████████████████| 51kB 229kB/s
Requirement already satisfied: Flask in /home/mark/.virtualenvs/flask_env/lib/python3.6/site-packages (from flask-script) (1.0.2)
Requirement already satisfied: Werkzeug>=0.14 in /home/mark/.virtualenvs/flask_env/lib/python3.6/site-packages (from Flask->flask-script) (0.14.1)
Requirement already satisfied: itsdangerous>=0.24 in /home/mark/.virtualenvs/flask_env/lib/python3.6/site-packages (from Flask->flask-script) (1.1.0)
Requirement already satisfied: click>=5.1 in /home/mark/.virtualenvs/flask_env/lib/python3.6/site-packages (from Flask->flask-script) (7.0)
Requirement already satisfied: Jinja2>=2.10 in /home/mark/.virtualenvs/flask_env/lib/python3.6/site-packages (from Flask->flask-script) (2.10)
Requirement already satisfied: MarkupSafe>=0.23 in /home/mark/.virtualenvs/flask_env/lib/python3.6/site-packages (from Jinja2>=2.10->Flask->flask-script) (1.1.0)
Building wheels for collected packages: flask-script
Running setup.py bdist_wheel for flask-script ... done
Stored in directory: /home/mark/.cache/pip/wheels/1c/17/70/4598e6dba4bec58c1b59552c6409272aea31978ab8159f11a1
Successfully built flask-script
Installing collected packages: flask-script
Successfully installed flask-script-2.0.6
(flask_env) [email protected]:~/PycharmProjects/flask_one$
使用flask-script
安装好了,不会用,怎么办?
在pycharm中点flask_script想进去看看,结果只进入了__init__.py中,看到如下内容:
class Manager(object):
"""
Controller class for handling a set of commands.
Typical usage::
class Print(Command):
def run(self):
print "hello"
app = Flask(__name__)
manager = Manager(app)
manager.add_command("print", Print())
if __name__ == "__main__":
manager.run()
On command line::
python manage.py print
> hello
:param app: Flask instance, or callable returning a Flask instance.
:param with_default_commands: load commands **runserver** and **shell**
by default.
:param disable_argcomplete: disable automatic loading of argcomplete.
"""
使用方式一
导入flask_script中的Manager,Command
自定义的命令需要在Command的子类中重写run方法,在此方法中定义命令需要做什么事
实例化Manager(可以接收一个Flask对象作为参数),调用Manager对象的add_command(‘命令‘, 自定义命令类实例)
from flask_script import Manager, Command
from app import app # Flask对象
class TestCommand(Command):
"""
测试命令
"""
def run(self): # 重写Command的run方法
# 使用命令在控制台输出信息
print("server run on xxx:80...")
manager = Manager(app) # 将flask_script与Flask联系起来
manager.add_command(‘test‘, TestCommand())
if __name__ == ‘__main__‘:
manager.run()
在manage.py中执行manage.run()可以查看这个manage中包含的命令详情
/home/mark/.virtualenvs/flask_env/bin/python3.6 /home/mark/PycharmProjects/flask_one/manage.py
usage: manage.py [-?] {test,shell,runserver} ...
positional arguments:
{test,shell,runserver}
test 测试命令
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
Process finished with exit code 2
在命令行执行python manage.py test
(flask_env) [email protected]:~/PycharmProjects/flask_one$ python manage.py test
server run on xxx:80...
使用方式二
导入flask_script中的Manager,实例化之后使用@manager.command装饰器装饰一个函数,这样,这个函数名就成为一个命令,函数中的代码会在执行这个命令后执行。
from flask_script import Manager
from app import app
manager = Manager(app)
@manager.command
def music():
"""
小妞,给爷唱一个
"""
print("客官不可以,不可以摸我那里....")
if __name__ == ‘__main__‘:
manager.run()
使用manager.run()查看
/home/mark/PycharmProjects/flask_one/manage.py
usage: manage.py [-?] {music,shell,runserver} ...
positional arguments:
{music,shell,runserver}
music 小妞,给爷唱一个
shell Runs a Python shell inside Flask application context.
runserver Runs the Flask development server i.e. app.run()
在命令行执行python manage.py music
(flask_env) [email protected]:~/PycharmProjects/flask_one$ python manage.py music
客官不可以,不可以摸我那里....
使用方式三
将命令定义在其他模块中,再引入到manage.py,将manage.py作为主命令模块。
from flask_script import Manager
# 不作为主命令模块,也就是说命令行是python manage.py xxx..
# 使用manage.py 而不是当前模块,这里的Manager()就不用传如Flask对象了
db_manager = Manager()
@db_manager.command
def migrate():
"""
数据迁移命令
"""
print("执行数据迁移...")
在manage.py中的引入方式:manger.add_command(‘prefix‘,manager对象)
from flask_script import Manager
from app import app
from db_manager import db_manager
manager = Manager(app)
# db是前缀 执行命令方式 python manage.py db migrate
manager.add_command(‘db‘, db_manager)
if __name__ == ‘__main__‘:
manager.run()
执行结果:
(flask_env) [email protected]:~/PycharmProjects/flask_one$ python manage.py db migrate
执行数据迁移...
其他使用方式
可以使用manger.option()
装饰器
命令函数可以接收参数
弹出确认操作:
@db_manager.command
def drop_data():
if prompt_bool("你真的要删除这些数据吗?后果自负哦..
"
"输入y删除,n取消"):
print(‘数据已删除...‘)
else:
print("就知道你不敢")
----------------------------------------
(flask_env) [email protected]:~/PycharmProjects/flask_one$ python manage.py db drop_data
你真的要删除这些数据吗?后果自负哦..
输入y删除,n取消 [n]: n
就知道你不敢
(flask_env) [email protected]:~/PycharmProjects/flask_one$
最后
以上是关于遇见Flask-Script的主要内容,如果未能解决你的问题,请参考以下文章