8.Flask-Script

 Flask-script的做用是能夠經過命令行的形式操做flask。安裝方式:pip install flask-scriptpython

1.1.command裝飾器

(1)建立manage.pysql

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終端運行django

python manage.py greet

# 「你好」

 

 1.2.option裝飾器flask

manage.pysession

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終端添加用戶app

python manage.py add_user -u derek -a 18


#添加的用戶名是:derek,年齡是:18

 

1.3. 實例:模擬django經過命令添加超級管理員函數

flask-script_demo.pyspa

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

相關文章
相關標籤/搜索