Flask擴展flask-script文檔中文翻譯

Flask擴展flask-script文檔中文翻譯

Flask-Script擴展提供向Flask插入外部腳本的功能。包括運行一個開發用的服務器,一個定製的 Python shell,設置數據庫的腳本,cronjobs,以及其餘的運行在web應用以外的命令行任務。html

Flask-Script和Flask自己的工做方式相似。只須要定義和添加能從命令行中被Manager實例調用的 命令便可。python

'''
# manage.py

from flask.ext.script import Manager
from myapp import app

manager = Manager(app)
@manager.command
def hello():
    print "hello"

if __name__ == "__main__":
    manager.run()

只要像上面同樣定義你本身的命令腳本,就能夠在命令行中以下調用他們:git

'''
python manage.py hello
> hello

Flask-Script的源代碼和bug追蹤見 GitHubgithub

安裝Flask-Script

可使用pip或者easy_install安裝裝:web

'''
pip install Flask-Script

或者下載最新開發版本:sql

'''
git clone https://github.com/techniq/flask-script.git
cd flask-script
python setup.py develop

若是你使用virtualenv,需保證把Flask-Script和你的Flask應用安裝在同一virtualenv環境下。shell

建立而且運行命令

首先,建立一個Python模塊運行你的命令腳本。能夠任意起名,例如manage.py。數據庫

無需把全部的命令都放在同一個文件裏,例如,在一個大型項目中,能夠把相關聯的命令放在不一樣的文件裏。flask

在你的manage.py文件中,必須有一個Manager實例。Manager類將追蹤全部的在命令行中調用的命令和處理過程的調用運行 狀況:服務器

'''
from flask.ext.script import Manager

app = Flask(__name__)
# configure your app

manager = Manager(app)

if __name__ == "__main__":
    manager.run()

調用 manager.run()將啓動Manger實例接收命令行中的命令。

Manager只有一個參數:一個Flask實例。若是你想用工場模式,那也能夠是一個函數或者其餘的返回Flask實例的玩意兒。

其次,建立而且加入命令。有三種方法可建立命令:

  • 建立Command的子類
  • 使用 @command 修飾符
  • 使用 @option 修飾符

下面是一個簡單的例子,建立一個Hello命令,該命令只是簡單的輸出「hello word」。

'''
from flask.ext.script import Command

class Hello(Command):
    "prints hello world"

    def run(self):
        print "hello world"

再把上面建立的Hello命令加入Manager實例:

'''
manager.add_command('hello', Hello())

很明顯,上面的語句須要在manager.run()以前運行。如今執行下面的命令:

'''
python manage.py hello
> hello world

也可傳給Command實例的run方法一個字典:

'''
manager.run({'hello' : Hello()})

Command class 必須定義一個run方法。定義的位置和參數依賴於你的定義的命令的參數。詳見下文。

運行下面的命令獲取可使用的命令及其描述的列表:

'''
python manage.py

經過運行下面的命令獲取一個特定命令的幫助,這將輸出這個命令的docstring。

'''
python manage.py runserver -h

上面的第一種方法是最適用的,但也是最麻煩的。對於簡單的命令,只須要使用Command實例的@command修飾符。

@manager.command
def hello():
    "Just say hello"
    print "hello"

這種方法建立的命令的運行方式和Command類建立的運行方式是相同的。

'''
python manage.py hello
> hello

若是用Comman類來實現,下面的命令將輸出manage類的docstring:

'''
python manage.py -h
> Just say hello

最後,@option修飾符適用於更精細的命令行控制:

'''
@manager.option('-n', '--name', help='Your name')
def hello(name):
    print "hello", name

後面會有更詳細的對@option的介紹。

增長命令行參數

大多數命令都帶有參數。仍是上面的例子,若是不只僅是打印"hello world",還想輸出一個額外的名字,如:

python manage.py hello --name=Joe
hello Joe

或者短參數:

python manage.py hello -n Joe

爲實現這一功能,須要使用Command類的option_list屬性。

from flask.ext.script import Command, Manager, Option

class Hello(Command):

    option_list = (
        Option('--name', '-n', dest='name'),
    )

    def run(self, name):
        print "hello %s" % name

長參數和短參數都是存儲在Option實例中。詳見API部分。

另外一種方法是爲你的Command類定義一個get——options方法,這將在但願依賴運行實例返回值來獲得參數時很是有效。

class Hello(Command):

    def __init__(self, default_name='Joe'):
        self.default_name=default_name

    def get_options(self):
        return [
            Option('-n', '--name', dest='name', default=self.default_name),
        ]

    def run(self, name):
        print "hello",  name

若使用@command修飾符,參數將直接自動的從函數的參數中獲取:

@manager.command
def hello(name):
    print "hello", name

> python manage.py hello Joe
hello Joe

或者使用可選參數:

@manager.command
def hello(name="Fred")
	print hello, name

調用方法以下:

> python manage.py hello --name=Joe
hello Joe

或者:

> python manage.py hello -n Joe
hello Joe

這裏須要注意:

-n 是由參數的第一個字母決定的。因此"name" > "-n"

其次,-h選項一般輸出命令的幫助文檔,因此避免使用h開頭的參數。

同時,須要注意選項參數是boolean值,例如:

@manage.command
def verify(verified=False):
    """
    Checks if verified
    """
    print "VERIFIED?", "YES" if verified else "NO"

只能這樣調用:

> python manage.py verify
VERIFIED? NO

> python manage.py verify -v
VERIFIED? YES

> python manage.py verify --verified
VERIFIED? YES

@command修飾符隨便簡單好用,但在複雜狀況下,@option是更好的選擇:

@manager.option('-n', '--name', dest='name', default='joe')
def hello(name):
    print "hello", name

能夠增長更多的選項參數:

@manager.option('-n', '--name', dest='name', default='joe')
@manager.option('-u', '--url', dest='url', default=None)
def hello(name, url):
    if url is None:
        print "hello", name
    else:
        print "hello", name, "from", url

能夠這樣調用: > python manage.py hello -n Joe -u reddit.com hello Joe from reddit.com

或者:

> python manage.py hello --name=Joe --url=reddit.com
hello Joe from reddit.com

向manager加入配置項

配置項也能夠傳給Manager實例。這是你能夠設置傳給Flask應用的配置項以便一條命令便可完成。例如,你可使用一個標 志來爲你的應用設置配置文件。例如:

def create_app(config=None):

    app = Flask(__name__)
    if config is not None:
        app.config.from_pyfile(config)
    # configure your app...
    return app

可使用命令行定義配置文件參數,例如使用一條命令設置數據庫,能夠根據生產環境和開發環境選用不一樣的配置文件。

爲實現傳配置參數,可使用add_option()方法,這和Option的參數同樣。

manager.add_option('-c', '--config', dest='config', required=False)

同其餘Flask-Script配置同樣,能夠在任何地方使用上面的語句,但確保在manager.run()以前執行。

假設你有下面的命令:

@manager.command
def hello(name):
    uppercase = app.config.get('USE_UPPERCASE', False)
    if uppercase:
        name = name.upper()
    print hello, name

> python manage.py hello joe -c dev.cfg
hello JOE

注意,」config「選項並無傳給上面的hello命令。

爲保證manage的選項能正常工做,須要傳一個工廠函數給Manager的構造器,而不是一個Flask實例。上面既是能夠簡單的示 例。

獲取用戶輸入

Flask-Script擁有一組helper函數來獲取用戶在命令行中的輸入,例如:

from flask.ext.script import Manager, prompt_bool

from myapp import app
from myapp.models import db

manager = Manager(app)

@manager.command
def dropdb():
    if prompt_bool(
        "Are you sure you want to lose all your data"):
        db.drop_all()

執行以下:

python manage.py dropdb
> Are you sure you want to lose all your data ? [N]

從下文API中獲取更多關於prompt functions的內容。

默認命令

Flask-Script擁有一對預設的命令,你能夠加入或者定製:Server and Shell。

Server命令運行Flask的開發server,它帶有一個可選的端口參數,默認是5000。

from flask.ext.script import Server, Manager
from myapp import create_app

manager = Manager(create_app)
manager.add_command("runserver", Server())

if __name__ == "__main__":
    manager.run()

運行以下:

python manage.py runserver

Server命令有一組命令行參數,運行python manage.py runserver -h 獲取詳細信息。你也能夠在構造函數中從新定義默認 行爲:

server = Server(host="0.0.0.0", port=9000)

無需贅言,開發Server不是爲生產環境準備的。

Shell名令啓動一個Python shell。能夠穿進去一個make_context參數,這個參數必須是一個字典。默認狀況下,將返回你的 Flask應用實例。

from flask import app

from flask.ext.script import Shell, Manager

from myapp import app
from myapp import models
from myapp.models import db

def _make_context():
    return dict(app=app, db=db, models=models)

manager = Manager(create_app)
manager.add_command("shell", Shell(make_context=_make_context))

這將對於你但願在shell引入一組默認的包很是有利,無需再輸入不少import語句。

Shell命令將使用IPthon,若是安裝了的話。不然,默認使用標準Python shell。你能夠用兩種方法關閉這一 行爲:傳use_ipython參數給Shell構造器,或者在命令行中傳標記--no-ipython。

shell = Shell(use_ipython=False)

也有一個shell修飾符,你能夠在函數上下文中使用。

@manager.shell
def make_shell_context():
    return dict(app=app, db=db, models=models)

這將使這個命令成爲shell的默認執行的命令。

> python manage.py shell

默認命令shell和runserver是默認引入的,而且帶有這兩個命令的默認選項。若你想用其餘命令替代默認的命令,只要重寫 add_command()或者修飾符。若你傳給Manager的構造器一個with_default_commands=False參數,則這些命令不會被載入。

manager = Manager(app, with_default_commands=False)

Sub-Managers A Sub-Manager is an instance of Manager added as a command to another Manager

To create a submanager:

sub_manager = Manager()

manager = Manager(self.app) manager.add_command("sub_manager", sub_manager) Restrictions A sub-manager does not provide an app instance/factory when created, it defers the calls to it’s parent Manager’s A sub-manager inhert’s the parent Manager’s app options (used for the app instance/factory) A sub-manager does not get default commands added to itself (by default) A sub-manager must be added the primary/root Manager instance via add_command(sub_manager) A sub-manager can be added to another sub-manager as long as the parent sub-manager is added to the primary/root Manager New in version 0.5.0.

Note to extension developers Extension developers can easily create convenient sub-manager instance within their extensions to make it easy for a user to consume all the available commands of an extension.

Here is an example how a database extension could provide (ex. database.py):

manager = Manager(usage="Perform database operations")

@manager.command def drop(): "Drops database tables" if prompt_bool("Are you sure you want to lose all your data"): db.drop_all()

@manager.command def create(default_data=True, sample_data=False): "Creates database tables from sqlalchemy models" db.create_all() populate(default_data, sample_data)

@manager.command def recreate(default_data=True, sample_data=False): "Recreates database tables (same as issuing 'drop' and then 'create')" drop() create(default_data, sample_data)

@manager.command def populate(default_data=False, sample_data=False): "Populate database with default data" from fixtures import dbfixture

if default_data:
    from fixtures.default_data import all
    default_data = dbfixture.data(*all)
    default_data.setup()

if sample_data:
    from fixtures.sample_data import all
    sample_data = dbfixture.data(*all)
    sample_data.setup()

Then the user can register the sub-manager to their primary Manager (within manage.py):

manager = Manager(app)

from flask.ext.database import manager as database_manager manager.add_command("database", database_manager) The commands will then be available:

python manage.py database

Please provide a command:

Perform database operations create Creates database tables from sqlalchemy models drop Drops database tables populate Populate database with default data recreate Recreates database tables (same as issuing 'drop' and then 'create') Accessing local proxies The Manager runs the command inside a Flask test context. This means that you can access request-local proxies where appropriate, such as current_app, which may be used by extensions.

API class flask_script.Manager(app=None, with_default_commands=None, usage=None, disable_argcomplete=False) 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 Parameters: app – Flask instance or callable returning a Flask instance. with_default_commands – load commands runserver and shell by default. disable_argcomplete – disable automatic loading of argcomplete. run(commands=None, default_command=None) Prepares manager to receive command line input. Usually run inside 「if name == 「main」 block in a Python script.

Parameters: commands – optional dict of commands. Appended to any commands added using add_command(). default_command – name of default command to run if no arguments passed. add_option(*args, **kwargs) Adds an application-wide option. This is useful if you want to set variables applying to the application setup, rather than individual commands.

For this to work, the manager must be initialized with a factory function rather than an instance. Otherwise any options you set will be ignored.

The arguments are then passed to your function, e.g.:

def create_app(config=None): app = Flask(name) if config: app.config.from_pyfile(config)

return app

manager = Manager(create_app) manager.add_option("-c", "--config", dest="config", required=False) and are evoked like this:

python manage.py -c dev.cfg mycommand Any manager options passed in the command line will not be passed to the command.

Arguments for this function are the same as for the Option class.

add_command(name, command) Adds command to registry.

Parameters: command – Command instance command(func) Decorator to add a command function to the registry.

Parameters: func – command function.Arguments depend on the options. option(*args, **kwargs) Decorator to add an option to a function. Automatically registers the function - do not use together with @command. You can add as many @option calls as you like, for example:

@option('-n', '--name', dest='name') @option('-u', '--url', dest='url') def hello(name, url): print "hello", name, url Takes the same arguments as the Option constructor.

shell(func) Decorator that wraps function in shell command. This is equivalent to:

def _make_context(app): return dict(app=app)

manager.add_command("shell", Shell(make_context=_make_context)) The decorated function should take a single 「app」 argument, and return a dict.

For more sophisticated usage use the Shell class.

option(*args, **kwargs) Decorator to add an option to a function. Automatically registers the function - do not use together with @command. You can add as many @option calls as you like, for example:

@option('-n', '--name', dest='name') @option('-u', '--url', dest='url') def hello(name, url): print "hello", name, url Takes the same arguments as the Option constructor.

class flask_script.Command Base class for creating commands.

run() Runs a command. This must be implemented by the subclass. Should take arguments as configured by the Command options.

get_options() By default, returns self.option_list. Override if you need to do instance-specific configuration.

class flask_script.Shell(banner=None, make_context=None, use_ipython=True, use_bpython=True) Runs a Python shell inside Flask application context.

Parameters: banner – banner appearing at top of shell when started make_context – a callable returning a dict of variables used in the shell namespace. By default returns a dict consisting of just the app. use_bpython – use BPython shell if available, ignore if not. The BPython shell can be turned off in command line by passing the –no-bpython flag. use_ipython – use IPython shell if available, ignore if not. The IPython shell can be turned off in command line by passing the –no-ipython flag. class flask_script.Server(host='127.0.0.1', port=5000, use_debugger=True, use_reloader=True, threaded=False, processes=1, passthrough_errors=False, **options) Runs the Flask development server i.e. app.run()

Parameters: host – server host port – server port use_debugger – if False, will no longer use Werkzeug debugger. This can be overriden in the command line by passing the -d flag. use_reloader – if False, will no longer use auto-reloader. This can be overriden in the command line by passing the -r flag. threaded – should the process handle each request in a separate thread? processes – number of processes to spawn passthrough_errors – disable the error catching. This means that the server will die on errors but it can be useful to hook debuggers in (pdb etc.) options – werkzeug.run_simple() options. class flask_script.Option(*args, **kwargs) Stores positional and optional arguments for ArgumentParser.add_argument.

Parameters: name_or_flags – Either a name or a list of option strings, e.g. foo or -f, –foo action – The basic type of action to be taken when this argument is encountered at the command-line. nargs – The number of command-line arguments that should be consumed. const – A constant value required by some action and nargs selections. default – The value produced if the argument is absent from the command-line. type – The type to which the command-line arg should be converted. choices – A container of the allowable values for the argument. required – Whether or not the command-line option may be omitted (optionals only). help – A brief description of what the argument does. metavar – A name for the argument in usage messages. dest – The name of the attribute to be added to the object returned by parse_args(). class flask_script.Group(*options, **kwargs) Stores argument groups and mutually exclusive groups for ArgumentParser.add_argument_group http://argparse.googlecode.com/svn/trunk/doc/other-methods.html#argument-groups or ArgumentParser.add_mutually_exclusive_group http://argparse.googlecode.com/svn/trunk/doc/other-methods.html#add_mutually_exclusive_group.

Note: The title and description params cannot be used with the exclusive or required params.

Parameters: options – A list of Option classes to add to this group title – A string to use as the title of the argument group description – A string to use as the description of the argument group exclusive – A boolean indicating if this is an argument group or a mutually exclusive group required – A boolean indicating if this mutually exclusive group must have an option selected flask_script.prompt(name, default=None) Grab user input from command line.

Parameters: name – prompt text default – default value if no input provided. flask_script.prompt_bool(name, default=False, yes_choices=None, no_choices=None) Grabs user input from command line and converts to boolean value.

Parameters: name – prompt text default – default value if no input provided. yes_choices – default ‘y’, ‘yes’, ‘1’, ‘on’, ‘true’, ‘t’ no_choices – default ‘n’, ‘no’, ‘0’, ‘off’, ‘false’, ‘f’ flask_script.prompt_pass(name, default=None) Grabs hidden (password) input from command line.

Parameters: name – prompt text default – default value if no input provided. flask_script.prompt_choices(name, choices, default=None, resolve=<function lower at 0x7f3ba568ba28>, no_choice=('none', )) Grabs user input from command line from set of provided choices.

Parameters: name – prompt text choices – list or tuple of available choices. Choices may be single strings or (key, value) tuples. default – default value if no input provided. no_choice – acceptable list of strings for 「null choice」

相關文章
相關標籤/搜索