遇见Flask-Script,,Flask-Scri


Flask-Script是Flask的命令行扩展包,使用它可以通过命令行的形式操作Flask项目, 例如,可通过命令启动一个发版本的服务器,设置数据库和定时任务等。

类似Django的manage.py提供的命令,不同的是使用flask-script可以自定义更多的命令。

Install flask-script

一般在虚拟环境中安装

(flask_env) mark@ocarina:~/PycharmProjects/flask_one$ pip install flask-scriptCollecting 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/4598e6dba4bec58c1b59552c6409272aea31978ab8159f11a1Successfully built flask-scriptInstalling collected packages: flask-scriptSuccessfully installed flask-script-2.0.6(flask_env) mark@ocarina:~/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, Commandfrom 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.pyusage: 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 exitProcess finished with exit code 2

在命令行执行python manage.py test

(flask_env) mark@ocarina:~/PycharmProjects/flask_one$ python manage.py testserver run on xxx:80...

使用方式二

导入flask_script中的Manager,实例化之后使用@manager.command装饰器装饰一个函数,这样,这个函数名就成为一个命令,函数中的代码会在执行这个命令后执行。

from flask_script import Managerfrom app import appmanager = Manager(app)@manager.commanddef music():    """    小妞,给爷唱一个    """    print("客官不可以,不可以摸我那里....")if __name__ == ‘__main__‘:    manager.run()

使用manager.run()查看

/home/mark/PycharmProjects/flask_one/manage.pyusage: 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) mark@ocarina:~/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.commanddef migrate():    """    数据迁移命令    """    print("执行数据迁移...")

在manage.py中的引入方式:manger.add_command(‘prefix‘,manager对象)

from flask_script import Managerfrom app import appfrom db_manager import db_managermanager = Manager(app)# db是前缀 执行命令方式 python manage.py db migratemanager.add_command(‘db‘, db_manager)if __name__ == ‘__main__‘:    manager.run()

执行结果:

(flask_env) mark@ocarina:~/PycharmProjects/flask_one$ python manage.py db migrate执行数据迁移...

其他使用方式

可以使用manger.option()装饰器

命令函数可以接收参数

弹出确认操作:

@db_manager.commanddef drop_data():    if prompt_bool("你真的要删除这些数据吗?后果自负哦..\t\n"                   "输入y删除,n取消"):        print(‘数据已删除...‘)    else:        print("就知道你不敢")----------------------------------------(flask_env) mark@ocarina:~/PycharmProjects/flask_one$ python manage.py  db drop_data你真的要删除这些数据吗?后果自负哦..    输入y删除,n取消 [n]: n就知道你不敢(flask_env) mark@ocarina:~/PycharmProjects/flask_one$ 

最后

更详细的资料在官方文档。

遇见Flask-Script

评论关闭