8.Flask-Script
Flask-Script
Flask-script的作用是可以通过命令行的形式操作flask。安装方式:pip install flask-script
1.1.command装饰器
(1)创建manage.py
from flask_script import Manager from flask_scripts_demo import app manager = Manager(app) @manager.command #这个装饰器把函数变成在终端可以运行的命令 def greet(): print('你好') if __name__ == '__main__': manager.run()
(2)执行命令
在cmd终端运行
python manage.py greet # “你好”
1.2.option装饰器
manage.py
from flask_script import Manager from flask_scripts_demo import app manager = Manager(app) @manager.command #这个装饰器把函数变成在终端可以运行的命令 def greet(): print('你好') #如果函数需要传递参数就用option装饰器 @manager.option("-u","--username",dest="username") #第一个参数是简称 @manager.option("-a","--age",dest="age") def add_user(username,age): print("添加的用户名是:%s,年龄是:%s"%(username,age)) if __name__ == '__main__': manager.run()
在cmd终端添加用户
python manage.py add_user -u derek -a 18 #添加的用户名是:derek,年龄是:18
1.3. 实例:模拟django通过命令添加超级管理员
flask-script_demo.py
from flask import Flask from flask_sqlalchemy import SQLAlchemy import config app = Flask(__name__) app.config.from_object(config) db = SQLAlchemy(app) class BackendUser(db.Model): __tablename__ = 'backend_user' id = db.Column(db.Integer,primary_key=True,autoincrement=True) username = db.Column(db.String(50),nullable=False) email = db.Column(db.String(50),nullable=False) db.create_all() @app.route('/') def hello_world(): return 'Hello World!' if __name__ == '__main__': app.run()
manage.py
from flask_script import Manager from flask_scripts_demo import app from flask_scripts_demo import BackendUser,db manager = Manager(app) @manager.option("-u","--username",dest="username") @manager.option("-e","--email",dest="email") def add_user(username,email): user = BackendUser(username=username,email=email) db.session.add(user) db.session.commit() if __name__ == '__main__': manager.run()
cmd终端添加用户到数据库
python manage.py add_user -u derek -e 111@qq.com