設定の処理の仕方(Configuration Handling) Configuration Handling

アプリケーションにある種の設定が必要です。デバッグモードの切り替え、secret keyの設定、その他の環境固有なもののように、アプリケーションの環境に依存して変更したいであろう異なる設定があるでしょう。 Applications need some kind of configuration. There are different settings you might want to change depending on the application environment like toggling the debug mode, setting the secret key, and other such environment-specific things.

Flaskの設計のやり方では普通、アプリケーションを開始するときは設定情報が利用可能であることを要求します。設定情報はコードの中へハードコードでき、それは多くの小さいアプリケーションに対してはそれほど悪いことではありませんが、もっと良いやり方もあります。 The way Flask is designed usually requires the configuration to be available when the application starts up. You can hard code the configuration in the code, which for many small applications is not actually that bad, but there are better ways.

設定をどうやって読み込むかにかかわらず、利用可能な設定オブジェクトで読み込んだ設定値を保持します: Flaskオブジェクトのconfig属性です。これはFlask自身がある種の設定値を置き、Flask拡張も設定値を置くことがある場所です。しかしながら、これはあなたが独自の設定を持てる場所でもあります。 Independent of how you load your config, there is a config object available which holds the loaded configuration values: The :attr:`~flask.Flask.config` attribute of the :class:`~flask.Flask` object. This is the place where Flask itself puts certain configuration values and also where extensions can put their configuration values. But this is also where you can have your own configuration.

設定の基本 Configuration Basics

configは、実際にはdicitonaryのサブクラスで、どんなdictionaryとも同じようなやり方で変更できます: The :attr:`~flask.Flask.config` is actually a subclass of a dictionary and can be modified just like any dictionary::

app = Flask(__name__)
app.config['TESTING'] = True

ある種の設定値はFlaskオブジェクトへも送られるため、それらはFlaskオブジェクトを使っても読み取りおよび書き込みできます(訳注: 例えばapp.config['TESTING']が、Flaskオブジェクトであるappの属性app.testingでもアクセスできるようになります): Certain configuration values are also forwarded to the :attr:`~flask.Flask` object so you can read and write them from there::

app.testing = True

一度に複数のキーを更新するには、dict.update()メソッドを使用できます: To update multiple keys at once you can use the :meth:`dict.update` method::

app.config.update(
    TESTING=True,
    SECRET_KEY=b'_5#y2L"F4Q8z\n\xec]/'
)

environmentとdebugの目玉機能(Environment and Debug Features) Environment and Debug Features

ENVDEBUGの設定値は特殊で、もしもappが準備を開始した(has begun setting up)後でそれらを変更すると、整合性のない振る舞いをすることがあります。environment(訳注: ENV設定値のような意味合い)とデバッグモード(訳注: DEBUG設定値のような意味合い)を信頼性を保ちながら設定するために、Flaskは環境変数を使用します。 The :data:`ENV` and :data:`DEBUG` config values are special because they may behave inconsistently if changed after the app has begun setting up. In order to set the environment and debug mode reliably, Flask uses environment variables.

Flask、Flask拡張、その他Sentryのようなプログラムへ、どんな文脈(context)でFlaskを実行しているかを伝えるときに、environmentが使用されます。それはFLASK_ENV環境変数で制御され、その標準設定はproducitonです。 The environment is used to indicate to Flask, extensions, and other programs, like Sentry, what context Flask is running in. It is controlled with the :envvar:`FLASK_ENV` environment variable and defaults to ``production``.

FLASK_ENVdevelopmentに設定すると、デバッグモードが有効になります。flask runは、デバッグモードでは標準設定でインタラクティブなデバッガとリローダ(訳注: アプリのソースコードを変更したとき再読み込みする機能)を使用するようになります。environment(訳注: 通常はFLASK_ENV環境変数を使って設定するENV設定値のこと)とは別にデバッグモードを制御するには、FLASK_DEBUGフラグを使います。 Setting :envvar:`FLASK_ENV` to ``development`` will enable debug mode. ``flask run`` will use the interactive debugger and reloader by default in debug mode. To control this separately from the environment, use the :envvar:`FLASK_DEBUG` flag.

Changelog

バージョン 1.0 で変更: デバッグモードと分けてenvironmentを制御するためにFLASK_ENVが追加されました。environmentをdevelopmentにするとデバッグモードを有効にします。

Flaskを開発(development)のenvironmentへ変更してデバッグモードを有効にするには、FLASK_ENVを以下のように設定します: To switch Flask to the development environment and enable debug mode, set :envvar:`FLASK_ENV`::

$ export FLASK_ENV=development
$ flask run

(Windowsでは、exportの代わりにsetを使用します。) (On Windows, use ``set`` instead of ``export``.)

上記のように環境変数を使用することを推奨します。ENVDEBUGをconfigまたはコードの中で設定することは可能ですが、そのようにはしないことを強く勧めます。configまたはコードの中で設定した値はflaskコマンドでは早い段階で読み取ることができず、そしていくつかのシステムまたはFlask拡張は、それらが読み取られるより前の値で既に設定を済ませてしまっているかもしれません。 Using the environment variables as described above is recommended. While it is possible to set :data:`ENV` and :data:`DEBUG` in your config or code, this is strongly discouraged. They can't be read early by the ``flask`` command, and some systems or extensions may have already configured themselves based on a previous value.

組込みの設定値 Builtin Configuration Values

以下の設定値はFlaskで内部的に使用されます: The following configuration values are used internally by Flask:

ENV

appをどのenvironmentで走らせるかを指定します。FlaskとFlask拡張は、デバッグモードの有効化のように、environmentに基づいて振る舞いを有効にする場合があります。env属性は、この設定キーに対応付けられます(訳注: app.config['ENV']のようにもapp.envのようにもアクセスできます)。これは、FLASK_ENV環境変数によって設定され、コードの中で設定された場合には期待通りに振る舞わないかもしれません。 What environment the app is running in. Flask and extensions may enable behaviors based on the environment, such as enabling debug mode. The :attr:`~flask.Flask.env` attribute maps to this config key. This is set by the :envvar:`FLASK_ENV` environment variable and may not behave as expected if set in code.

本番環境にデプロイするときは、development設定を有効にしないでください。 **Do not enable development when deploying in production.**

標準設定: 'production' Default: ``'production'``

Changelog

バージョン 1.0 で追加.

DEBUG

デバッグモードを有効にするかどうかを指定します。flask runを使用して開発サーバを開始するときは、捕捉されない例外はインタラクティブなデバッガで表示され、コードが変更されたときは再読み込みされるようになります。debug属性がこの設定キーに対応付けられます(訳注:app.config['DEBUG']のようにもapp.debugのようにもアクセスできます)。これはENV'development'のときは有効になり、FLASK_DEBUG環境変数によって上書きされます。コードの中で設定された場合には期待通りに振る舞わないかもしれません。 Whether debug mode is enabled. When using ``flask run`` to start the development server, an interactive debugger will be shown for unhandled exceptions, and the server will be reloaded when code changes. The :attr:`~flask.Flask.debug` attribute maps to this config key. This is enabled when :data:`ENV` is ``'development'`` and is overridden by the ``FLASK_DEBUG`` environment variable. It may not behave as expected if set in code.

本番環境にデプロイするときは、デバッグモードを有効にしないでください。 **Do not enable debug mode when deploying in production.**

標準設定: もしもENV'developmentであればTrue、そうでなければFalse Default: ``True`` if :data:`ENV` is ``'development'``, or ``False`` otherwise.

TESTING

テストモードを有効にします。例外が発生したとき、appのエラーハンドラで処理させる代わりに、影響を伝搬させるようにします。より容易なテストを促進させるために、Flask拡張も振る舞いを変えるかもしれません。あなたが自分のテストをするときは、これは有効にするべきです。 Enable testing mode. Exceptions are propagated rather than handled by the the app's error handlers. Extensions may also change their behavior to facilitate easier testing. You should enable this in your own tests.

標準設定: False Default: ``False``

PROPAGATE_EXCEPTIONS

例外が発生したとき、appのエラーハンドラで処理させる代わりに、発生させ直しします。設定されていない場合、これはTESTINGまたはDEBUGが有効なときは暗黙的にtrueになります。 Exceptions are re-raised rather than being handled by the app's error handlers. If not set, this is implicitly true if ``TESTING`` or ``DEBUG`` is enabled.

標準設定: None Default: ``None``

PRESERVE_CONTEXT_ON_EXCEPTION

例外が発生したとき、request context(訳注: リクエスト固有なデータなどを格納し、リクエストの期間中はどこからでも保持・操作できるようにするためのオブジェクト)を取り除きません。もし設定されていない場合、これはDEBUGがtrueなときはtrueです。これは、エラーが起きたときにデバッガがリクエストのデータを調べることを可能にし、通常は直接設定する必要はありません。 Don't pop the request context when an exception occurs. If not set, this is true if ``DEBUG`` is true. This allows debuggers to introspect the request data on errors, and should normally not need to be set directly.

標準設定: None Default: ``None``

TRAP_HTTP_EXCEPTIONS

もしもHTTPException-タイプの例外に対する処理(handler)がない場合、単純なエラーレスポンスとして返す代わりに、インタラクティブなデバッガで処理できるように、その例外を発生させ直します。 If there is no handler for an ``HTTPException``-type exception, re-raise it to be handled by the interactive debugger instead of returning it as a simple error response.

標準設定: False Default: ``False``

TRAP_BAD_REQUEST_ERRORS

(無効の時は)リクエストのdictから、argsformのような存在しないキーへアクセスしようとしたときは、400 Bad Requestエラーページを返します。エラーとして扱う代わりに未処理の例外として扱い、インタラクティブなデバッガを使えるようにするには、これを有効にします。これはTRAP_HTTP_EXCEPTIONSをより具体的にしたバージョンです。もし未設定の場合、デバッグモードで有効になります。 Trying to access a key that doesn't exist from request dicts like ``args`` and ``form`` will return a 400 Bad Request error page. Enable this to treat the error as an unhandled exception instead so that you get the interactive debugger. This is a more specific version of ``TRAP_HTTP_EXCEPTIONS``. If unset, it is enabled in debug mode.

標準設定: None Default: ``None``

SECRET_KEY

セッションのクッキーを安全に署名するために使用され、さらに自分のアプリケーションやFlask拡張が必要とする、その他のあらゆるセキュリティに関する用途で使用されるsecret keyです。これはでたらめな(random)長い文字列のバイトにするべきであり、unicodeも許容されています。例えば、以下のコマンドの出力結果を自分の設定にコピーします: A secret key that will be used for securely signing the session cookie and can be used for any other security related needs by extensions or your application. It should be a long random string of bytes, although unicode is accepted too. For example, copy the output of this to your config::

$ python -c 'import os; print(os.urandom(16))'
b'_5#y2L"F4Q8z\n\xec]/'

質問を投稿するときやコードをコミットするときは、このsecret keyを表に出さないようにしてください。 **Do not reveal the secret key when posting questions or committing code.**

標準設定: None Default: ``None``

セッションのクッキーの名前です。同じ名前を使ったクッキーを既に持っている場合には、変更が可能です。 The name of the session cookie. Can be changed in case you already have a cookie with the same name.

標準設定: 'session' Default: ``'session'``

セッションのクッキーが有効になるドメインに該当させるルールを指定します。もし設定されていない場合、クッキーはSERVER_NAMEのすべてのサブドメインで有効になります。もしFalseの場合、クッキーのドメインは設定されません。 The domain match rule that the session cookie will be valid for. If not set, the cookie will be valid for all subdomains of :data:`SERVER_NAME`. If ``False``, the cookie's domain will not be set.

標準設定: None Default: ``None``

セッションのクッキーが有効となるパスを指定します。もし設定されていない場合、クッキーはAPPLICATION_ROOTの下、またはAPPLICATION_ROOTが設定されていない場合は/の下で有効になります。 The path that the session cookie will be valid for. If not set, the cookie will be valid underneath ``APPLICATION_ROOT`` or ``/`` if that is not set.

標準設定: None Default: ``None``

セキュリティのために、「HTTP only」と印付られたクッキーへJavaScriptがアクセスすることを、ブラウザは許可しないようにします(訳注: 「HTTP only」と指定されたクッキーへはJavaScriptからアクセスできないように、ブラウザ側で処理するという意味合いだと思います)。 Browsers will not allow JavaScript access to cookies marked as "HTTP only" for security.

標準設定: True Default: ``True``

クッキーが「secure」と印付られていた場合、HTTPS上のリクエストを使ったときだけブラウザがそのクッキーを送信するようにします。これが意味をなすには、アプリケーションはHTTPSを使用してサービスを提供している必要があります。 Browsers will only send cookies with requests over HTTPS if the cookie is marked "secure". The application must be served over HTTPS for this to make sense.

標準設定: False Default: ``False``

クッキーが外部サイトからのリクエストと一緒に送信されるやり方を制限します。'Lax'(推奨)または'Strict'が設定可能です。Set-Cookieオプションを確認してください。 Restrict how cookies are sent with requests from external sites. Can be set to ``'Lax'`` (recommended) or ``'Strict'``. See :ref:`security-cookie`.

標準設定: None Default: ``None``

Changelog

バージョン 1.0 で追加.

PERMANENT_SESSION_LIFETIME

もしsession.permanentがtrueである場合は、クッキーの消滅期限は未来のこの秒数に設定されます。datetime.timedeltaまたはintのいずれかが可能です。 If ``session.permanent`` is true, the cookie's expiration will be set this number of seconds in the future. Can either be a :class:`datetime.timedelta` or an ``int``.

Flaskの標準設定でのクッキー実装は、暗号法上の署名がこの値より古くないかを検証します。 Flask's default cookie implementation validates that the cryptographic signature is not older than this value.

標準設定: timedelta(days=31) (2678400 秒) Default: ``timedelta(days=31)`` (``2678400`` seconds)

SESSION_REFRESH_EACH_REQUEST

session.permanentがtrueのとき、すべてのレスポンスで一緒にクッキーを送信するかを制御します。毎回クッキーを送信する(標準設定)と、クッキーの消滅からセッションを守ることが、より高い信頼性で可能ですが、しかしより多くの帯域(通信データ量)を使用します。持続しない(non-permanent)セッションは影響を受けません。 Control whether the cookie is sent with every response when ``session.permanent`` is true. Sending the cookie every time (the default) can more reliably keep the session from expiring, but uses more bandwidth. Non-permanent sessions are not affected.

標準設定: True Default: ``True``

USE_X_SENDFILE

ファイルを供給するとき、Flaskでデータを供給する代わりにX-Sendfileヘッダを設定します。例えばApacheのような、いくつかのwebサーバーではこれを認識してデータをより効率的に供給します。そのようなサーバを使用しているときだけこれは意味をなします。 When serving files, set the ``X-Sendfile`` header instead of serving the data with Flask. Some web servers, such as Apache, recognize this and serve the data more efficiently. This only makes sense when using such a server.

標準設定: False Default: ``False``

SEND_FILE_MAX_AGE_DEFAULT

ファイルを供給するとき、この値の秒数にキャッシュ制御最大年齢(cache control max age)を設定します。datetime.timedeltaまたはintのいずれかに設定可能です。アプリケーションまたはblueprint上でget_send_file_max_age()を使用すると、ファイルごとにこの値を上書きします。 When serving files, set the cache control max age to this number of seconds. Can either be a :class:`datetime.timedelta` or an ``int``. Override this value on a per-file basis using :meth:`~flask.Flask.get_send_file_max_age` on the application or blueprint.

標準設定: timedelta(hours=12) (43200 秒) Default: ``timedelta(hours=12)`` (``43200`` seconds)

SERVER_NAME

どのホストとポートを使用するかアプリケーションに知らせます。サブドメインのルートとのマッチングのサポートに必要になります。 Inform the application what host and port it is bound to. Required for subdomain route matching support.

もし設定された場合、SESSION_COOKIE_DOMAINが設定されていないときはセッションのクッキーのドメインに使用されます。最近の(modern)webブラウザはドット(「.」)のないドメインに対してはクッキーの設定を許可しません。ドメインを(自分のPCなど)ローカルで使用するには、ローカルのhostsファイルにappへの経路を提供(route)する名前を何でもよいので追加してください: If set, will be used for the session cookie domain if :data:`SESSION_COOKIE_DOMAIN` is not set. Modern web browsers will not allow setting cookies for domains without a dot. To use a domain locally, add any names that should route to the app to your ``hosts`` file. ::

127.0.0.1 localhost.dev

もし設定された場合、url_forが外側のURL(訳注:引数「_external」を指定した、パスだけでなく、ドメイン名なども含めたURL)を生成できるのは、request contextの代わりに、application contextを使ってだけになります。 If set, ``url_for`` can generate external URLs with only an application context instead of a request context.

標準設定: None Default: ``None``

APPLICATION_ROOT

アプリケーションに、アプリケーションサーバ / webサーバによってどのパスに設置(mount)されているかを知らせます。これはリクエストのcontextの外側で(訳注: request contextが登録できてない状態という意味合い、リクエストのコンテキスト(The Request Context)参照)URLを生成するために使用されます(リクエストの内側では、振り分け機能(dispatcher)が代わりにSCRIPT_NAME(訳注: アプリケーションのエンドポイントのURLでのパス部分とほぼ同じ意味合い)を設定する責任を担います; 振り分け(dispatch)設定の例はApplication Dispatchingを確認してください)(訳注: SCRIPT_NAMEなどについては、wsgiの仕様参照<https://wsgi.readthedocs.io/en/latest/definitions.html>)。 Inform the application what path it is mounted under by the application / web server. This is used for generating URLs outside the context of a request (inside a request, the dispatcher is responsible for setting ``SCRIPT_NAME`` instead; see :ref:`Application Dispatching <app-dispatch>` for examples of dispatch configuration).

SESSION_COOKIE_PATHが設定されてない場合、セッションのクッキーのパスに使用されます。 Will be used for the session cookie path if ``SESSION_COOKIE_PATH`` is not set.

標準設定: '/' Default: ``'/'``

PREFERRED_URL_SCHEME

request contextの中でないとき、外側のURL(訳注: 「url_for」に引数「_external」を指定した、パスだけでなく、ドメイン名なども含めたURLとほぼ同じ意味合い)を生成するためにこのscheme(訳注: URLのプロトコル(「://」の左側)部分)を使用します。 Use this scheme for generating external URLs when not in a request context.

標準設定: 'http' Default: ``'http'``

MAX_CONTENT_LENGTH

受信リクエストのデータを、このバイト数より多くは読み取らないようにします。もし未設定であってリクエストがCONTENT_LENGTHを指定していない場合、セキュリティのために全くデータを読み取りません。 Don't read more than this many bytes from the incoming request data. If not set and the request does not specify a ``CONTENT_LENGTH``, no data will be read for security.

標準設定: None Default: ``None``

JSON_AS_ASCII

オブジェクトをASCIIにエンコードしたJSONへシリアライズします。もしこれが無効にされている場合、jsonifyによって、JSONはUnicode文字列、またはUTF-8へエンコードされてから返されます。テンプレートの中でJSONをJavaScriptへ変換するとき、これはセキュリティ上の問題を生じる可能性があり、したがって典型的には有効のままにしておくべきです。 Serialize objects to ASCII-encoded JSON. If this is disabled, the JSON will be returned as a Unicode string, or encoded as ``UTF-8`` by ``jsonify``. This has security implications when rendering the JSON into JavaScript in templates, and should typically remain enabled.

標準設定: True Default: ``True``

JSON_SORT_KEYS

JSONオブジェクトのキーをアルファベット順にソートします。これはPythonのhashのシード(訳注: 無作為な乱数を作るために使う補助データ)が何であっても同じようなデータにシリアライズされることを保証するため、キャッシュするときに便利です。推奨はされませんが、これを無効にすると、キャッシュを犠牲にする代わりに性能が向上する可能性があります。 Sort the keys of JSON objects alphabetically. This is useful for caching because it ensures the data is serialized the same way no matter what Python's hash seed is. While not recommended, you can disable this for a possible performance improvement at the cost of caching.

標準設定: True Default: ``True``

JSONIFY_PRETTYPRINT_REGULAR

jsonifyレスポンスで、人が読みやすいように改行、スペース、インデントをして出力するようにします。デバッグモードでは、常に有効にされます。 ``jsonify`` responses will be output with newlines, spaces, and indentation for easier reading by humans. Always enabled in debug mode.

標準設定: False Default: ``False``

JSONIFY_MIMETYPE

jsonifyレスポンスのmimetypeです。 The mimetype of ``jsonify`` responses.

標準設定: 'application/json' Default: ``'application/json'``

TEMPLATES_AUTO_RELOAD

テンプレートが変更されたとき、再読み込みします。もし未設定の場合、デバッグモードでは有効になります。 Reload templates when they are changed. If not set, it will be enabled in debug mode.

標準設定: None Default: ``None``

EXPLAIN_TEMPLATE_LOADING

テンプレートファイルがどのように読み込まれたかトレースするデバッグ情報をログします。テンプレートが読み込まれなかった、もしくは誤ったファイルが読み込まれて表示されたのが何故かを調べるときに役立つ場合があります。 Log debugging information tracing how a template file was loaded. This can be useful to figure out why a template was not loaded or the wrong file appears to be loaded.

標準設定: False Default: ``False``

クッキーのヘッダがこのバイト数よりも大きい場合に警告します。標準設定は4093です。大きなクッキーはブラウザにより何の反応もなしに無視される場合があります。この警告を無効にするには0に設定します。 Warn if cookie headers are larger than this many bytes. Defaults to ``4093``. Larger cookies may be silently ignored by browsers. Set to ``0`` to disable the warning.

Changelog

バージョン 1.0 で変更: LOGGER_NAMELOGGER_HANDLER_POLICYは削除されました。(ログの)設定に関する情報はログ処理(Logging)を確認してください。

FLASK_ENV環境変数を反映するためENVが追加されました。 Added :data:`ENV` to reflect the :envvar:`FLASK_ENV` environment variable.

セッションのクッキーのSameSiteオプションを制御するためにSESSION_COOKIE_SAMESITEが追加されました。 Added :data:`SESSION_COOKIE_SAMESITE` to control the session cookie's ``SameSite`` option.

Werkzeugからの警告を制御するためにMAX_COOKIE_SIZEが追加されました。 Added :data:`MAX_COOKIE_SIZE` to control a warning from Werkzeug.

バージョン 0.11 で追加: SESSION_REFRESH_EACH_REQUEST, TEMPLATES_AUTO_RELOAD, LOGGER_HANDLER_POLICY, EXPLAIN_TEMPLATE_LOADING

バージョン 0.10 で追加: JSON_AS_ASCII, JSON_SORT_KEYS, JSONIFY_PRETTYPRINT_REGULAR

バージョン 0.9 で追加: PREFERRED_URL_SCHEME

バージョン 0.8 で追加: TRAP_BAD_REQUEST_ERRORS, TRAP_HTTP_EXCEPTIONS, APPLICATION_ROOT, SESSION_COOKIE_DOMAIN, SESSION_COOKIE_PATH, SESSION_COOKIE_HTTPONLY, SESSION_COOKIE_SECURE

バージョン 0.7 で追加: PROPAGATE_EXCEPTIONS, PRESERVE_CONTEXT_ON_EXCEPTION

バージョン 0.6 で追加: MAX_CONTENT_LENGTH

バージョン 0.5 で追加: SERVER_NAME

バージョン 0.4 で追加: LOGGER_NAME

ファイルからの設定の読み取り(Configuring from Files) Configuring from Files

ファイルを分けて、理想的には実際のアプリケーションのパッケージからは外側にあるファイルで、そのファイルの中に設定を格納できる場合、設定をより便利に行えます。これは、様々なパッケージ処理ツール(Setuptoolsを使った展開(Deploying with Setuptools))を通して自分のアプリケーションをパッケージ化および配布できるようにし、そして最終的に設定ファイルを後から変更できるようにします。 Configuration becomes more useful if you can store it in a separate file, ideally located outside the actual application package. This makes packaging and distributing your application possible via various package handling tools (:ref:`distribute-deployment`) and finally modifying the configuration file afterwards.

したがって、よくあるパターンは以下のとおりです: So a common pattern is this::

app = Flask(__name__)
app.config.from_object('yourapplication.default_settings')
app.config.from_envvar('YOURAPPLICATION_SETTINGS')

これは、最初にyourapplication.default_settingsモジュールから設定を読み込み、それからYOURAPPLICATION_SETTINGS環境変数が指し示すファイルの内容を使って値を上書きします。この環境変数はLinuxまたはOS Xでは、サーバを開始する前にシェルの中でexportコマンドで設定できます: This first loads the configuration from the `yourapplication.default_settings` module and then overrides the values with the contents of the file the :envvar:`YOURAPPLICATION_SETTINGS` environment variable points to. This environment variable can be set on Linux or OS X with the export command in the shell before starting the server::

$ export YOURAPPLICATION_SETTINGS=/path/to/settings.cfg
$ python run-app.py
 * Running on http://127.0.0.1:5000/
 * Restarting with reloader...

Windowsシステムでは代わりに組込みのsetを使用します: On Windows systems use the `set` builtin instead::

> set YOURAPPLICATION_SETTINGS=\path\to\settings.cfg

設定ファイルそれ自身は実際にはPythonファイルです。大文字の値だけが(訳注: 設定ファイルであるPythonファイルのモジュール変数で変数名が大文字だけのものだけが)、実際にはconfigオブジェクトの中へ後で格納されます。従って、自分の設定のキーでは、確実に大文字を使用するようにしてください。 The configuration files themselves are actual Python files. Only values in uppercase are actually stored in the config object later on. So make sure to use uppercase letters for your config keys.

以下は設定ファイルの例です: Here is an example of a configuration file::

# Example configuration
DEBUG = False
SECRET_KEY = b'_5#y2L"F4Q8z\n\xec]/'

設定の読み込みは確実に早い段階で行ってください、そうすればFlask拡張が開始時に設定へアクセスできるようになります。configオブジェクトには、個別のファイルから(設定を)読み込む他の手段もあります。完全なリファレンスについては、Configオブジェクトのドキュメントを読んでください。 Make sure to load the configuration very early on, so that extensions have the ability to access the configuration when starting up. There are other methods on the config object as well to load from individual files. For a complete reference, read the :class:`~flask.Config` object's documentation.

環境変数からの設定の読み取り(Configuring from Environment Variables) Configuring from Environment Variables

環境変数を使用して設定ファイルを指し示すことに加えて、環境(environment)から直接設定値を制御することが便利(もしくは必要)なことがあるかもしれません。 In addition to pointing to configuration files using environment variables, you may find it useful (or necessary) to control your configuration values directly from the environment.

環境変数はLinuxまたはOS Xでは、サーバを開始する前にシェルの中でexportコマンドで設定できます: Environment variables can be set on Linux or OS X with the export command in the shell before starting the server::

$ export SECRET_KEY='5f352379324c22463451387a0aec5d2f'
$ export MAIL_ENABLED=false
$ python run-app.py
 * Running on http://127.0.0.1:5000/

Windowsシステムでは代わりに組込みのsetを使用します: On Windows systems use the ``set`` builtin instead::

> set SECRET_KEY='5f352379324c22463451387a0aec5d2f'

このアプローチは直感的に使えますが、環境変数は文字列(string)であることを覚えておくことが重要です -- それらはPythonの型へ自動的には変換(deserialize)されません。 While this approach is straightforward to use, it is important to remember that environment variables are strings -- they are not automatically deserialized into Python types.

以下は、環境変数を使用している設定ファイルの例です: Here is an example of a configuration file that uses environment variables::

import os

_mail_enabled = os.environ.get("MAIL_ENABLED", default="true")
MAIL_ENABLED = _mail_enabled.lower() in {"1", "t", "true"}

SECRET_KEY = os.environ.get("SECRET_KEY")

if not SECRET_KEY:
    raise ValueError("No SECRET_KEY set for Flask application")

Pythonでは、空の文字(empty string)以外のあらゆる値は、boolean型ではTrueに解釈され、もし環境(変数)ではFalseを意図して明示的に値を設定するときには配慮が必要になることに注意してください。 Notice that any value besides an empty string will be interpreted as a boolean ``True`` value in Python, which requires care if an environment explicitly sets values intended to be ``False``.

設定の読み込みは確実に早い段階で行ってください、そうすればFlask拡張が開始時に設定へアクセスできるようになります。configオブジェクトには、個別のファイルから(設定を)読み込む他の手段もあります。完全なリファレンスについては、Configクラスのドキュメントを読んでください。 Make sure to load the configuration very early on, so that extensions have the ability to access the configuration when starting up. There are other methods on the config object as well to load from individual files. For a complete reference, read the :class:`~flask.Config` class documentation.

設定のベストプラクティス Configuration Best Practices

前の方で示したやり方のマイナス面は、テストの実施が少々難しくなることです。この問題に対する100%のひとつだけの解決方法というのは一般的にありませんが、テスト時の経験を改善するために心に留めておいた方がよいことがいくつかあります: The downside with the approach mentioned earlier is that it makes testing a little harder. There is no single 100% solution for this problem in general, but there are a couple of things you can keep in mind to improve that experience:

  1. 関数の中で自分のアプリケーションを作成し、そのアプリケーションにblueprintを登録します。このやり方では、自分のアプリケーションの複数のインスタンスを作成し、ユニットテストをより容易にする異なる設定を取り付けることができます。必要に応じて設定を投入するために、このやり方を使用できます。 Create your application in a function and register blueprints on it. That way you can create multiple instances of your application with different configurations attached which makes unit testing a lot easier. You can use this to pass in configuration as needed.

  2. import時に設定情報が必要になるコードは書かないようにします。もしも設定情報へリクエストだけのアクセスをするよう自分自身を制限すれば、必要に応じて後からオブジェクトの再設定が可能です。 Do not write code that needs the configuration at import time. If you limit yourself to request-only accesses to the configuration you can reconfigure the object later on as needed.

開発環境 / 本番環境 Development / Production

殆どのアプリケーションでは2つ以上の設定を必要とします。少なくとも、本番環境のサーバと開発中に使うサーバとの設定は分けるべきです。これを扱う最も簡単なやり方は、バージョン管理の一部にして常に読み込まれる標準設定と、上記の例で言及したように必要に応じて値を上書きする分かれた設定を使用することです。 Most applications need more than one configuration. There should be at least separate configurations for the production server and the one used during development. The easiest way to handle this is to use a default configuration that is always loaded and part of the version control, and a separate configuration that overrides the values as necessary as mentioned in the example above::

app = Flask(__name__)
app.config.from_object('yourapplication.default_settings')
app.config.from_envvar('YOURAPPLICATION_SETTINGS')

それから、分かれたconfig.pyファイルを追加し、YOURAPPLICATION_SETTINGS=/path/to/config.pyをexportする必要があるだけで、出来上がりです。ただし、さらに別のやり方もあります。例えば、importやサブクラス作成も使えます。 Then you just have to add a separate :file:`config.py` file and export ``YOURAPPLICATION_SETTINGS=/path/to/config.py`` and you are done. However there are alternative ways as well. For example you could use imports or subclassing.

Django界隈で人気があるのは、from yourapplication.default_settings import *を設定ファイルの最初に置いておくことで設定ファイルの中でimportすることを明確にし、それから手作業で変更を上書きしていくことです。YOURAPPLICATION_MODEのような環境変数を調べることも可能で、それをproduction, developmentなどに設定しておき、その値に基づいて違うようにハードコードされたファイルをimportします。 What is very popular in the Django world is to make the import explicit in the config file by adding ``from yourapplication.default_settings import *`` to the top of the file and then overriding the changes by hand. You could also inspect an environment variable like ``YOURAPPLICATION_MODE`` and set that to `production`, `development` etc and import different hard-coded files based on that.

設定のためにクラスを使用し継承することも、興味深いパターンのひとつです: An interesting pattern is also to use classes and inheritance for configuration::

class Config(object):
    DEBUG = False
    TESTING = False
    DATABASE_URI = 'sqlite:///:memory:'

class ProductionConfig(Config):
    DATABASE_URI = 'mysql://user@localhost/foo'

class DevelopmentConfig(Config):
    DEBUG = True

class TestingConfig(Config):
    TESTING = True

このような設定を有効にするために必要なのは、ただfrom_object()を呼び出すだけです。 To enable such a config you just have to call into :meth:`~flask.Config.from_object`::

app.config.from_object('configmodule.ProductionConfig')

from_object()はクラスオブジェクトをインスタンス化しないことに注目してください。もしも、propertyへのアクセスなどをするためにクラスをインスタンス化する必要があるときは、from_object()を呼び出す前に実施する必要があります(訳注: 以下の例でfrom_objectの引数が「ProductionConfig()」と初期化しているところが該当): Note that :meth:`~flask.Config.from_object` does not instantiate the class object. If you need to instantiate the class, such as to access a property, then you must do so before calling :meth:`~flask.Config.from_object`::

from configmodule import ProductionConfig
app.config.from_object(ProductionConfig())

# Alternatively, import via string:
from werkzeug.utils import import_string
cfg = import_string('configmodule.ProductionConfig')()
app.config.from_object(cfg)

設定オブジェクトをインスタンス化すると、設定クラスの中で@propertyが使えるようになります: Instantiating the configuration object allows you to use ``@property`` in your configuration classes::

class Config(object):
    """Base config, uses staging database server."""
    DEBUG = False
    TESTING = False
    DB_SERVER = '192.168.1.56'

    @property
    def DATABASE_URI(self):         # Note: all caps
        return 'mysql://user@{}/foo'.format(self.DB_SERVER)

class ProductionConfig(Config):
    """Uses production database server."""
    DB_SERVER = '192.168.19.32'

class DevelopmentConfig(Config):
    DB_SERVER = 'localhost'
    DEBUG = True

class TestingConfig(Config):
    DB_SERVER = 'localhost'
    DEBUG = True
    DATABASE_URI = 'sqlite:///:memory:'

他にも多くの違うやり方があり、設定ファイルをどのように管理したいかはあなたしだいです。ただし、良いと推奨されることのリストは以下のとおりです: There are many different ways and it's up to you how you want to manage your configuration files. However here a list of good recommendations:

  • 標準設定をバージョン管理(対象)の中に残しておきます。値を上書きする前に、この標準設定の内容を(アプリケーションの)設定へ移すか、自分の設定ファイルへimportします。 Keep a default configuration in version control. Either populate the config with this default configuration or import it in your own configuration files before overriding values.

  • 環境変数を使用して設定を切り替えます。これはPythonインタプリタの外側から行うことができ、コードに全く触る必要なく異なる設定の間を素早く容易に切り替えられるため、開発とデプロイ(訳注: 本番環境への移行のような意味合い)を非常に容易にします。もしも異なるプロジェクトで作業することがよくある場合、自分用にvirtualenvをactivateし開発設定をexportするためにsourceする(訳注: こことは別にインストールのドキュメントで紹介していますが、Pythonでは「source <仮想環境の場所>/bin/activate」を実行すると仮想環境用の設定をexportして利用できるようになるvirtualenvという仕組みがあります)、自分独自のスクリプトさえ作成できます。 Use an environment variable to switch between the configurations. This can be done from outside the Python interpreter and makes development and deployment much easier because you can quickly and easily switch between different configs without having to touch the code at all. If you are working often on different projects you can even create your own script for sourcing that activates a virtualenv and exports the development configuration for you.

  • コードと設定を別々に本番環境のサーバへ押し入れる(push)ために、fabricのようなツールを本番環境で使用します。どのように実施するかについての詳細は、Deploying with Fabricパターンを調べてください。 Use a tool like `fabric`_ in production to push code and configurations separately to the production server(s). For some details about how to do that, head over to the :ref:`fabric-deployment` pattern.

インスタンスフォルダ Instance Folders

Changelog

バージョン 0.8 で追加.

Flask 0.8ではインスタンスフォルダを導入しました。Flaskは長い間、アプリケーションのフォルダからの相対パスを直接参照できるようにしていました(root_pathをとおして)。これは、多くの開発者がアプリケーションの隣に格納した設定を読み込むやり方でもありました。しかし残念ながら、root path(root_pathの設定値)がパッケージのコンテンツを参照してしまうパッケージ化が、アプリケーションにされていないときだけ、これはうまく働くものです。 Flask 0.8 introduces instance folders. Flask for a long time made it possible to refer to paths relative to the application's folder directly (via :attr:`Flask.root_path`). This was also how many developers loaded configurations stored next to the application. Unfortunately however this only works well if applications are not packages in which case the root path refers to the contents of the package.

Flask 0.8では新しい属性が導入されています: instance_pathです。それは「インスタンスフォルダ(instance folder)」と呼ばれる新しいコンセプトを参照します。インスタンスフォルダは、バージョン管理対象にはせず、デプロイ固有のものであるように設計されています。それは実行時に変化するものや設定ファイルを入れておくには、完璧な場所です。 With Flask 0.8 a new attribute was introduced: :attr:`Flask.instance_path`. It refers to a new concept called the “instance folder”. The instance folder is designed to not be under version control and be deployment specific. It's the perfect place to drop things that either change at runtime or configuration files.

Flaskアプリケーションを作成するときにインスタンスフォルダのパスを明示的に提供することも、Flaskがインスタンスフォルダを自動的に見つけ出すようにすることもできます。明示的に設定するにはinstance_pathパラメータを使用してください: You can either explicitly provide the path of the instance folder when creating the Flask application or you can let Flask autodetect the instance folder. For explicit configuration use the `instance_path` parameter::

app = Flask(__name__, instance_path='/path/to/instance/folder')

パスを提供するときは絶対パスにする必要があることを覚えておいてください。 Please keep in mind that this path *must* be absolute when provided.

instance_pathパラメータが提供されていない場合、以下の標準設定(default)の場所が使用されます: If the `instance_path` parameter is not provided the following default locations are used:

  • インストールされていないmodule: Uninstalled module::

    /myapp.py
    /instance
    
  • インストールされていないpackage: Uninstalled package::

    /myapp
        /__init__.py
    /instance
    
  • インストールされているmoduleまたはpackage: Installed module or package::

    $PREFIX/lib/python2.X/site-packages/myapp
    $PREFIX/var/myapp-instance
    

    $PREFIXはPythonのインストールでのプレフィックス(訳注: Pythonの主要なフォルダ・ファイルがインストールされた場所で、インストール時などに指定し、Python実行時に標準ライブラリなどのファイルを探すときは、自動的にプレフィックスの下を探します)です。これは/usrまたはvirtualenvのパスになることがあり得ます。そのプレフィックスに何が設定されたか確認するために、sys.prefixの値を表示することができます。 ``$PREFIX`` is the prefix of your Python installation. This can be ``/usr`` or the path to your virtualenv. You can print the value of ``sys.prefix`` to see what the prefix is set to.

configオブジェクトは相対ファイル名からの設定ファイルの読み込みを提供するため、望む場合は、instance path(instance_pathの設定値)からの相対ファイル名を介して(設定ファイルを)読み込むように変更することが可能です。設定ファイル中の相対パスの振る舞いは「application rootに対して相対的」と(標準設定の)「インスタンスフォルダに対して相対的」との間を切り替えることが、アプリケーションのコンストラクタでinstance_relative_configスイッチをとおして可能です。 Since the config object provided loading of configuration files from relative filenames we made it possible to change the loading via filenames to be relative to the instance path if wanted. The behavior of relative paths in config files can be flipped between “relative to the application root” (the default) to “relative to instance folder” via the `instance_relative_config` switch to the application constructor::

app = Flask(__name__, instance_relative_config=True)

moduleから設定を先読みして、それから、インスタンスフォルダがあれば、インスタンスフォルダにあるファイルの設定で上書きするようにFlaskを設定するやり方の、一通りの(不足のない)例がこちらです: Here is a full example of how to configure Flask to preload the config from a module and then override the config from a file in the instance folder if it exists::

app = Flask(__name__, instance_relative_config=True)
app.config.from_object('yourapplication.default_settings')
app.config.from_pyfile('application.cfg', silent=True)

インスタンスフォルダへのパスはinstance_pathをとおして見つけることができます。Flaskはインスタンスフォルダにあるファイルを開くショートカットも、open_instance_resource()によって提供します。 The path to the instance folder can be found via the :attr:`Flask.instance_path`. Flask also provides a shortcut to open a file from the instance folder with :meth:`Flask.open_instance_resource`.

両者の使用例: Example usage for both::

filename = os.path.join(app.instance_path, 'application.cfg')
with open(filename) as f:
    config = f.read()

# or via open_instance_resource:
with app.open_instance_resource('application.cfg') as f:
    config = f.read()