コマンドライン・インタフェース Command Line Interface

FlaskをインストールするとflaskスクリプトとClickコマンドライン・インタフェースをvirtualenvの中にインストールします。端末から実行されたとき、このスクリプトは組み込みの、Flask拡張の、およびアプリケーションで定義したコマンドへアクセスできるようにします。--helpオプションは、どのコマンドおよびオプションに関してもさらなる情報を与えます。 Installing Flask installs the ``flask`` script, a `Click`_ command line interface, in your virtualenv. Executed from the terminal, this script gives access to built-in, extension, and application-defined commands. The ``--help`` option will give more information about any commands and options.

アプリケーションの発見(Application Discovery) Application Discovery

flaskコマンドはあなたのアプリケーションではなくFlaskによってインストールされます; flaskコマンドがあなたのアプリケーションを使用するためには、アプリケーションがどこにあるかを伝える必要があります。アプリケーションをどのように読み込むかを指定するためにFLASK_APP環境変数が使用されます。 The ``flask`` command is installed by Flask, not your application; it must be told where to find your application in order to use it. The ``FLASK_APP`` environment variable is used to specify how to load the application.

UnixのBash(Linux, Mac, etc.): Unix Bash (Linux, Mac, etc.)::

$ export FLASK_APP=hello
$ flask run

WindowsのCMD: Windows CMD::

> set FLASK_APP=hello
> flask run

WindowsのPowerShell: Windows PowerShell::

> $env:FLASK_APP = "hello"
> flask run

FLASK_APPはアプリケーションを指定するための様々なオプションをサポートしていますが、殆どの使用状況はシンプルなものでしょう。典型的な環境変数の値は以下のとおりです: While ``FLASK_APP`` supports a variety of options for specifying your application, most use cases should be simple. Here are the typical values:

(何もなし) (nothing)

ファイルwsgi.pyがimportされ、自動的にアプリ(app)が見つけ出されます。これは、追加の引数を使用するfactoryからアプリケーションを作成するための容易な方法を提供します。 The file :file:`wsgi.py` is imported, automatically detecting an app (``app``). This provides an easy way to create an app from a factory with extra arguments.

FLASK_APP=hello

指定した名前(訳注: 上の例では「hello」にあたる部分)がimportされ、自動的にアプリ(app)またはfactory(create_app)が見つけ出されます。 The name is imported, automatically detecting an app (``app``) or factory (``create_app``).


FLASK_APPは3つの部分からなります: 必須ではない、そのときの作業ディレクトリ(current working directory)を設定するパスと、Pythonファイルまたはdotを使って示されたimportパス(dotted import path)と、必須ではない、インスタンスまたはfactoryの変数名です。もしその名前がfactoryの場合は、必要に応じてカッコ内で囲んだ引数を後ろにつけることができます。以下に示す変数の値は、これらの3つの部分のデモになります: ``FLASK_APP`` has three parts: an optional path that sets the current working directory, a Python file or dotted import path, and an optional variable name of the instance or factory. If the name is a factory, it can optionally be followed by arguments in parentheses. The following values demonstrate these parts:

FLASK_APP=src/hello

そのときの作業ディレクトリ(current working directory)をsrcに設定してからhelloをimportします。 Sets the current working directory to ``src`` then imports ``hello``.

FLASK_APP=hello.web

パスhello.webをimportします。 Imports the path ``hello.web``.

FLASK_APP=hello:app2

helloの中のFlaskインスタンスapp2を使用します。 Uses the ``app2`` Flask instance in ``hello``.

FLASK_APP="hello:create_app('dev')"

helloの中にあるfactoryのcreate_appを、文字列'dev'を引数に使って呼び出します。 The ``create_app`` factory in ``hello`` is called with the string ``'dev'`` as the argument.

もしFLASK_APPが設定されていない場合、flaskコマンドは「app」または「wsgi」を(「.py」ファイルとして、またはパッケージとして)importしようとし、そしてアプリケーションのインスタンスまたはfactoryを見つけ出そうとします。 If ``FLASK_APP`` is not set, the command will try to import "app" or "wsgi" (as a ".py" file, or package) and try to detect an application instance or factory.

与えられたimportの中で、flaskコマンドはappまたはapplicationという名前のアプリケーションのインスタンスを探し、それからそれ以外の名前も含めたあらゆるアプリケーションのインスタンスを探します。もしインスタンスが見つからなかった場合、flaskコマンドはcreate_appまたはmake_appという名前の、インスタンスを返すfactory関数を探します。 Within the given import, the command looks for an application instance named ``app`` or ``application``, then any application instance. If no instance is found, the command looks for a factory function named ``create_app`` or ``make_app`` that returns an instance.

もしアプリケーションのfactoryを呼び出すときは、もしfactoryがscript_infoという名前の引数を受け取る場合は、ScriptInfoのインスタンスがキーワード引数として渡されます。もしアプリケーションのfactoryが1つだけ引数を受け取り(環境変数の値で)factory名の後ろにカッコがない場合は、ScriptInfoのインスタンスが位置引数(positional argument)として渡されます。もしfactory名の後ろにカッコが続く場合は、その内容がPythonリテラルとして処理されてからfactory関数に引数として渡されます。これは、文字列(としてfactory関数へ渡す内容)が(環境変数の値の中では)引用符で囲まれていなければならないことを意味します。 When calling an application factory, if the factory takes an argument named ``script_info``, then the :class:`~cli.ScriptInfo` instance is passed as a keyword argument. If the application factory takes only one argument and no parentheses follow the factory name, the :class:`~cli.ScriptInfo` instance is passed as a positional argument. If parentheses follow the factory name, their contents are parsed as Python literals and passes as arguments to the function. This means that strings must still be in quotes.

開発用サーバの実行 Run the Development Server

runコマンドは開発用サーバを開始します。runコマンドは殆どのケースで、Flask.run()メソッドの代わりになります。: The :func:`run <cli.run_command>` command will start the development server. It replaces the :meth:`Flask.run` method in most cases. ::

$ flask run
 * Serving Flask app "hello"
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

警告

本番環境ではアプリケーションを走らせるためにこのコマンドを使わないでください。開発中だけ開発用サーバを使用してください。開発用サーバは便宜のために提供されていますが、安全、安定、効率的であるようには特に設計されていません。本番環境でどうやって実行するかについては展開の選択肢(Deployment Options)を確認してください。 Do not use this command to run your application in production. Only use the development server during development. The development server is provided for convenience, but is not designed to be particularly secure, stable, or efficient. See :ref:`deployment` for how to run in production.

シェルの開始(Open a Shell) Open a Shell

自分のアプリケーションの中でデータを調べるために、shellコマンドを使ってインタラクティブなPythonのシェルを開始できます。アプリケーションのcontextは有効(active)になり、アプリのインスタンスがimportされます。: To explore the data in your application, you can start an interactive Python shell with the :func:`shell <cli.shell_command>` command. An application context will be active, and the app instance will be imported. ::

$ flask shell
Python 3.6.2 (default, Jul 20 2017, 03:52:27)
[GCC 7.1.1 20170630] on linux
App: example
Instance: /home/user/Projects/hello/instance
>>>

その他に自動的にimportされるものを追加するには、shell_context_processor()を使用します。 Use :meth:`~Flask.shell_context_processor` to add other automatic imports.

環境(Environments) Environments

Changelog

バージョン 1.0 で追加.

Flaskアプリケーションが走る環境はFLASK_ENV環境変数により設定されます。もしその環境変数が設定されていない場合、productionが標準設定で使用されます。他に認識される環境はdevelopmentがあります。FlaskとFlask拡張は、実行される環境(FLASK_ENVの値など)に基づいて、有効化される振舞を選択することがあります。 The environment in which the Flask app runs is set by the :envvar:`FLASK_ENV` environment variable. If not set it defaults to ``production``. The other recognized environment is ``development``. Flask and extensions may choose to enable behaviors based on the environment.

もし環境がdevelopmentに設定されていた場合、flaskコマンドはデバッグモードを有効にし、flask runは、インタラクティブなデバッガと再読み込み機能(reloader)を有効にします。 If the env is set to ``development``, the ``flask`` command will enable debug mode and ``flask run`` will enable the interactive debugger and reloader.

$ FLASK_ENV=development flask run
 * Serving Flask app "hello"
 * Environment: development
 * Debug mode: on
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
 * Restarting with inotify reloader
 * Debugger is active!
 * Debugger PIN: 223-456-919

再読み込み機能(Reloader)による追加ファイルの監視 Watch Extra Files with the Reloader

developmentモードを使用しているとき、あなたがPythonコードまたはimportされているモジュールを変更するたびにreloaderが始動します。reloaderは、--extra-filesオプションまたはFLASK_RUN_EXTRA_FILES環境変数を使用して、追加ファイルを監視できます。複数のパスは:、もしくはWindowsでは;を使用して分けられます。 When using development mode, the reloader will trigger whenever your Python code or imported modules change. The reloader can watch additional files with the ``--extra-files`` option, or the ``FLASK_RUN_EXTRA_FILES`` environment variable. Multiple paths are separated with ``:``, or ``;`` on Windows.

$ flask run --extra-files file1:dirA/file2:dirB/
# or
$ export FLASK_RUN_EXTRA_FILES=file1:dirA/file2:dirB/
$ flask run
 * Running on http://127.0.0.1:8000/
 * Detected change in '/path/to/file1', reloading

デバッグモード Debug Mode

先に説明したとおり、デバッグモードはFLASK_ENVdevelopmentであるとき有効になります。もしデバッグモードを(FLASK_ENVから)分けて制御したい場合、FLASK_DEBUGを使用してください。値が1で有効になり、0で無効になります。 Debug mode will be enabled when :envvar:`FLASK_ENV` is ``development``, as described above. If you want to control debug mode separately, use :envvar:`FLASK_DEBUG`. The value ``1`` enables it, ``0`` disables it.

dotenvからの環境変数読み込み Environment Variables From dotenv

新しい端末を開くたびに毎回FLASK_APPを設定する代わりに、自動的に環境変数を設定するために、Flaskのdotenvサポートを使用できます。 Rather than setting ``FLASK_APP`` each time you open a new terminal, you can use Flask's dotenv support to set environment variables automatically.

もしpython-dotenvがインストールされている場合、flaskコマンドを実行すると.env.flaskenvの中で定義されている環境変数が設定されます。これは、新しい端末を開くたびに毎回手作業でFLASK_APPを設定し、いくつかの展開するサービス(deployment service)を機能させるやり方と同じような、環境変数を使った設定をする必要をなくすために使用できます If `python-dotenv`_ is installed, running the ``flask`` command will set environment variables defined in the files :file:`.env` and :file:`.flaskenv`. This can be used to avoid having to set ``FLASK_APP`` manually every time you open a new terminal, and to set configuration using environment variables similar to how some deployment services work.

.flaskenvで設定された変数は.envで設定されたもので上書きされ、それらは。コマンドラインで設定された変数で上書きされます。flaskenvは、例えばFLASK_APPのように、公開される変数として使用されるべきであり、一方.envはプライベートな変数を設定できるようにするために(ソースコード管理の)リポジトリにはコミットすべきではありません。 Variables set on the command line are used over those set in :file:`.env`, which are used over those set in :file:`.flaskenv`. :file:`.flaskenv` should be used for public variables, such as ``FLASK_APP``, while :file:`.env` should not be committed to your repository so that it can set private variables.

flaskを呼び出したディレクトリから親へと上りながら、それらのファイル(.envおよび.flaskenv)の場所を見つけるためにディレクトリが調べられます。そのときの作業ディレクトリ(current working directory)は、それらのファイル(.envおよび.flaskenv)のあった場所に設定され、その場所がプロジェクトの最上位のディレクトリであるという前提がおかれます。 Directories are scanned upwards from the directory you call ``flask`` from to locate the files. The current working directory will be set to the location of the file, with the assumption that that is the top level project directory.

それらのファイルはflaskコマンドもしくは呼び出されているrun()によってのみ読み込まれます。もしそれらのファイルを本番環境の中で走らせるときに読み込みたい場合、手動でload_dotenv()を呼び出す必要があります。 The files are only loaded by the ``flask`` command or calling :meth:`~Flask.run`. If you would like to load these files when running in production, you should call :func:`~cli.load_dotenv` manually.

コマンドオプションの設定 Setting Command Options

Clickはコマンドオプションの標準の値を環境変数から読み込むよう設定されています。それらの変数にはFLASK_COMMAND_OPTIONのパターンが使用されています。例えば、コマンドを実行するためのポートを設定するために、flask run --port 8000の代わりに以下を使用できます: Click is configured to load default values for command options from environment variables. The variables use the pattern ``FLASK_COMMAND_OPTION``. For example, to set the port for the run command, instead of ``flask run --port 8000``:

$ export FLASK_RUN_PORT=8000
$ flask run
 * Running on http://127.0.0.1:8000/

標準のコマンドオプションを制御するために、これらの値を.flaskenvファイルにFLASK_APPと同じように追加できます。 These can be added to the ``.flaskenv`` file just like ``FLASK_APP`` to control default command options.

dotenvの無効化 Disable dotenv

もしdotenvファイルを見つけたにもかかわらずpython-dotenvがインストールされていない場合、flaskコマンドはメッセージを表示します。 The ``flask`` command will show a message if it detects dotenv files but python-dotenv is not installed.

$ flask run
 * Tip: There are .env files present. Do "pip install python-dotenv" to use them.

FLASK_SKIP_DOTENV環境変数を設定することで、python-dotenvがインストールされていたときでさえもdotenvファイルを読み込まないようFlaskへ伝えることができます。これは、それらを手作業で読み込みたいときや、それらを既に読み込んでいるproject runner(訳注: コンパイル・テスト・パッケージ作成など、よく実施される一纒まり処理を、簡単な操作でまとめて実施できるようにする、makeコマンドのようなツールを指していると思います)を使用している場合には役立つでしょう。環境変数はアプリのロードより前に設定されている必要があり、そうでなければ期待したようには(アプリが)設定されないであろうことを忘れないでください。 You can tell Flask not to load dotenv files even when python-dotenv is installed by setting the ``FLASK_SKIP_DOTENV`` environment variable. This can be useful if you want to load them manually, or if you're using a project runner that loads them already. Keep in mind that the environment variables must be set before the app loads or it won't configure as expected.

$ export FLASK_SKIP_DOTENV=1
$ flask run

virtualenvからの環境変数読み込み Environment Variables From virtualenv

もしdotenvのサポートをインストールしたくない場合でも、virtualenvのactivateスクリプトの最後へ追加することで環境変数を設定することができます。virtualenvをactivateすると、変数が設定されます。 If you do not want to install dotenv support, you can still set environment variables by adding them to the end of the virtualenv's :file:`activate` script. Activating the virtualenv will set the variables.

UnixのBashでは、venv/bin/activateに追加します: Unix Bash, :file:`venv/bin/activate`::

$ export FLASK_APP=hello

WindowsのCMDでは、venv\Scripts\activate.batに追加します: Windows CMD, :file:`venv\\Scripts\\activate.bat`::

> set FLASK_APP=hello

.flaskenvは(ソースコード管理の)リポジトリへコミットして、リポジトリをチェックアウトしたプロジェクトではどこでも自動的に機能するようにできるため、このやり方よりは、dotenvのサポートを使用する方が好ましいです。 It is preferred to use dotenv support over this, since :file:`.flaskenv` can be committed to the repository so that it works automatically wherever the project is checked out.

独自のコマンド(Custom Commands) Custom Commands

flaskコマンドはClickを使用して実装されています。コマンド作成に関する全体を網羅した情報についてはClickプロジェクトのドキュメントを確認してください。 The ``flask`` command is implemented using `Click`_. See that project's documentation for full information about writing commands.

以下の例は、name引数を受け取るcreate-userコマンドを追加します。: This example adds the command ``create-user`` that takes the argument ``name``. ::

import click
from flask import Flask

app = Flask(__name__)

@app.cli.command("create-user")
@click.argument("name")
def create_user(name):
    ...
$ flask create-user admin

以下の例は同じコマンドを追加しますが、グループの中のコマンドのひとつであるuser createとして追加します。これは関連する複数のコマンドを編成したいときに便利です。 This example adds the same command, but as ``user create``, a command in a group. This is useful if you want to organize multiple related commands. ::

import click
from flask import Flask
from flask.cli import AppGroup

app = Flask(__name__)
user_cli = AppGroup('user')

@user_cli.command('create')
@click.argument('name')
def create_user(name):
    ...

app.cli.add_command(user_cli)
$ flask user create demo

自分の独自コマンドをどのようにテストするかの概要についてはCLIコマンドのテスト(Testing CLI Commands)を確認してください。 See :ref:`testing-cli` for an overview of how to test your custom commands.

Blueprintsを使ったコマンドの登録 Registering Commands with Blueprints

もし自分のアプリケーションがblueprintを使っている場合、CLIコマンドを直接それらのblueprintに適宜登録できます。blueprintがアプリケーションに登録されたとき、関連付けられているコマンドはflaskコマンドから利用可能になります。標準設定では、それらのコマンドはblueprintの名前に合致(match)するグループへと入れ子(nest)にされます。 If your application uses blueprints, you can optionally register CLI commands directly onto them. When your blueprint is registered onto your application, the associated commands will be available to the ``flask`` command. By default, those commands will be nested in a group matching the name of the blueprint.

from flask import Blueprint

bp = Blueprint('students', __name__)

@bp.cli.command('create')
@click.argument('name')
def create(name):
    ...

app.register_blueprint(bp)
$ flask students create alice

Blueprintオブジェクトを作成するときcli_groupパラメータを指定することによって、もしくは後からapp.register_blueprint(bp, cli_group='...')を使って、コマンドのグループ名を変更できます。以下は同じ処理になります: You can alter the group name by specifying the ``cli_group`` parameter when creating the :class:`Blueprint` object, or later with :meth:`app.register_blueprint(bp, cli_group='...') <Flask.register_blueprint>`. The following are equivalent:

bp = Blueprint('students', __name__, cli_group='other')
# or
app.register_blueprint(bp, cli_group='other')
$ flask other create alice

cli_group=Noneを指定すると入れ子を削除して、コマンドを直接アプリケーションのレベルへまとめます。 Specifying ``cli_group=None`` will remove the nesting and merge the commands directly to the application's level:

bp = Blueprint('students', __name__, cli_group=None)
# or
app.register_blueprint(bp, cli_group=None)
$ flask create alice

アプリケーションのコンテキスト(Application Context) Application Context

Flaskアプリのclicommand()デコレータ(decorator)を使って追加されたコマンドは、(訳注: Flask内で各リクエストのapplication contextをstack構造で格納・管理している領域に)pushされたapplication contextを使って実行されるため、あなたのコマンドおよびFlask拡張はapp(のインスタンス)およびその設定情報にアクセスが可能です。もしFlaskのデコレータの代わりにClickのcommand()デコレータを使ってコマンドを作成した場合、同じ振る舞いを得るためにwith_appcontext()使用できます。: Commands added using the Flask app's :attr:`~Flask.cli` :meth:`~cli.AppGroup.command` decorator will be executed with an application context pushed, so your command and extensions have access to the app and its configuration. If you create a command using the Click :func:`~click.command` decorator instead of the Flask decorator, you can use :func:`~cli.with_appcontext` to get the same behavior. ::

import click
from flask.cli import with_appcontext

@click.command()
@with_appcontext
def do_work():
    ...

app.cli.add_command(do_work)

もしコマンドがcontextを必要としないことが分かっている場合は、application contextへのアクセスを無効にできます: If you're sure a command doesn't need the context, you can disable it::

@app.cli.command(with_appcontext=False)
def do_work():
    ...

プラグイン Plugins

Flaskはflask.commandsentry pointで指定されたコマンドを自動的に読み込みます。これは、インストールされたときにはコマンドを追加したいFlask拡張にとっては便利です。entry pointはsetup.pyの中で指定されます: Flask will automatically load commands specified in the ``flask.commands`` `entry point`_. This is useful for extensions that want to add commands when they are installed. Entry points are specified in :file:`setup.py` ::

from setuptools import setup

setup(
    name='flask-my-extension',
    ...,
    entry_points={
        'flask.commands': [
            'my-command=flask_my_extension.commands:cli'
        ],
    },
)

flask_my_extension/commands.pyの内側ではClickオブジェクトをexportできます: Inside :file:`flask_my_extension/commands.py` you can then export a Click object::

import click

@click.command()
def cli():
    ...

一度あなたのFlaskプロジェクトと同じvirtualenvに(上記の例の)パッケージがインストールされると、コマンドを呼び出すためにflask my-commandを実行できます。 Once that package is installed in the same virtualenv as your Flask project, you can run ``flask my-command`` to invoke the command.

独自のスクリプト Custom Scripts

app factoryパターンを使用しているとき、自分のClickスクリプトを定義できるとさらに便利かもしれません。FLASK_APPを使用してFlaskが自分のアプリケーションを読み込めるようにする代わりに、自分独自のclickオブジェクトを作成し、console scriptのentry pointとしてexportできます。 When you are using the app factory pattern, it may be more convenient to define your own Click script. Instead of using ``FLASK_APP`` and letting Flask load your application, you can create your own Click object and export it as a `console script`_ entry point.

FlaskGroupのインスタンスを作成して、それにfactoryを渡します: Create an instance of :class:`~cli.FlaskGroup` and pass it the factory::

import click
from flask import Flask
from flask.cli import FlaskGroup

def create_app():
    app = Flask('wiki')
    # other setup
    return app

@click.group(cls=FlaskGroup, create_app=create_app)
def cli():
    """Management script for the Wiki application."""

setup.pyの中でentry pointを定義します: Define the entry point in :file:`setup.py`::

from setuptools import setup

setup(
    name='flask-my-extension',
    ...,
    entry_points={
        'console_scripts': [
            'wiki=wiki:cli'
        ],
    },
)

virtualenvの中でアプリケーションを編集可能モード(editable mode)でインストールすると独自スクリプトが利用可能になります。FLASK_APPを設定する必要はないことに注意してください。: Install the application in the virtualenv in editable mode and the custom script is available. Note that you don't need to set ``FLASK_APP``. ::

$ pip install -e .
$ wiki run

独自スクリプトの中のエラー Errors in Custom Scripts

独自スクリプトを使用するとき、もしmoduleレベルのコードでエラーを導入してしまった場合、entry pointがもはや読み込めなくなるため、再読み込み機能(reloader)に障害が起きます(fail)。 When using a custom script, if you introduce an error in your module-level code, the reloader will fail because it can no longer load the entry point.

flaskコマンドは、あなたのコードとは分かれているため、このような問題は持たず、そのため殆どのケースでは推奨されます。 The ``flask`` command, being separate from your code, does not have this issue and is recommended in most cases.

PyCharm Integration

Prior to PyCharm 2018.1, the Flask CLI features weren't yet fully integrated into PyCharm. We have to do a few tweaks to get them working smoothly. These instructions should be similar for any other IDE you might want to use.

In PyCharm, with your project open, click on Run from the menu bar and go to Edit Configurations. You'll be greeted by a screen similar to this:

screenshot of pycharm's run configuration settings

There's quite a few options to change, but once we've done it for one command, we can easily copy the entire configuration and make a single tweak to give us access to other commands, including any custom ones you may implement yourself.

Click the + (Add New Configuration) button and select Python. Give the configuration a good descriptive name such as "Run Flask Server". For the flask run command, check "Single instance only" since you can't run the server more than once at the same time.

Select Module name from the dropdown (A) then input flask.

The Parameters field (B) is set to the CLI command to execute (with any arguments). In this example we use run, which will run the development server.

You can skip this next step if you're using dotenvからの環境変数読み込み. We need to add an environment variable (C) to identify our application. Click on the browse button and add an entry with FLASK_APP on the left and the Python import or file on the right (hello for example).

Next we need to set the working directory (D) to be the folder where our application resides.

If you have installed your project as a package in your virtualenv, you may untick the PYTHONPATH options (E). This will more accurately match how you deploy the app later.

Click Apply to save the configuration, or OK to save and close the window. Select the configuration in the main PyCharm window and click the play button next to it to run the server.

Now that we have a configuration which runs flask run from within PyCharm, we can copy that configuration and alter the Script argument to run a different CLI command, e.g. flask shell.