欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Flask之flask-script模塊使用

 更新時間:2018年07月26日 09:08:06   作者:不_一  
Flask Script擴展提供向Flask插入外部腳本的功能,這篇文章主要介紹了Flask之flask-script模塊使用,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧

Flask Script擴展提供向Flask插入外部腳本的功能,包括運行一個開發(fā)用的服務器,一個定制的Python shell,設置數(shù)據(jù)庫的腳本,cronjobs,及其他運行在web應用之外的命令行任務;使得腳本和系統(tǒng)分開;

Flask Script和Flask本身的工作方式類似,只需定義和添加從命令行中被Manager實例調用的命令;

官方文檔:http://flask-script.readthedocs.io/en/latest/

創(chuàng)建并運行命令

首先,創(chuàng)建一個Python模板運行命令腳本,可起名為manager.py;

在該文件中,必須有一個Manager實例,Manager類追蹤所有在命令行中調用的命令和處理過程的調用運行情況;

Manager只有一個參數(shù)——Flask實例,也可以是一個函數(shù)或其他的返回Flask實例;

調用manager.run()啟動Manager實例接收命令行中的命令;

#-*-coding:utf8-*- 
from flask_script import Manager 
from debug import app 
 
manager = Manager(app) 
 
if __name__ == '__main__': 
 manager.run() 

其次,創(chuàng)建并加入命令;

有三種方法創(chuàng)建命令,即創(chuàng)建Command子類、使用@command修飾符、使用@option修飾符;

第一種——創(chuàng)建Command子類

Command子類必須定義一個run方法;

舉例:創(chuàng)建Hello命令,并將Hello命令加入Manager實例;

from flask_script import Manager ,Server
from flask_script import Command 
from debug import app 
 
manager = Manager(app) 


class Hello(Command): 
 'hello world' 
 def run(self): 
  print 'hello world' 

#自定義命令一:
manager.add_command('hello', Hello()) 
# 自定義命令二:

manager.add_command("runserver", Server()) #命令是runserver
if __name__ == '__main__': 
 manager.run() 

執(zhí)行如下命令:

python manager.py hello
> hello world

 python manager.py runserver
> hello world

第二種——使用Command實例的@command修飾符

#-*-coding:utf8-*- 
from flask_script import Manager 
from debug import app 
 
manager = Manager(app) 
 
@manager.command 
def hello(): 
 'hello world' 
 print 'hello world' 
 
if __name__ == '__main__': 
 manager.run() 

該方法創(chuàng)建命令的運行方式和Command類創(chuàng)建的運行方式相同;

python manager.py hello
> hello world

第三種——使用Command實例的@option修飾符

復雜情況下,建議使用@option;

可以有多個@option選項參數(shù);

from flask_script import Manager 
from debug import app 
 
manager = Manager(app) 
 
@manager.option('-n', '--name', dest='name', help='Your name', default='world') #命令既可以用-n,也可以用--name,dest="name"用戶輸入的命令的名字作為參數(shù)傳給了函數(shù)中的name
@manager.option('-u', '--url', dest='url', default='www.csdn.com') #命令既可以用-u,也可以用--url,dest="url"用戶輸入的命令的url作為參數(shù)傳給了函數(shù)中的url

def hello(name, url): 
'hello world or hello <setting name>' 
 print 'hello', name 
 print url 
 
if __name__ == '__main__': 
 manager.run() 

運行方式如下:

python manager.py hello
>hello world
>www.csdn.com

python manager.py hello -n sissiy -u www.sissiy.com
> hello sissiy
>www.sissiy.com

python manager.py hello -name sissiy -url www.sissiy.com
> hello sissiy
>www.sissiy.com

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。

您可能感興趣的文章:

相關文章

最新評論