設定の処理の仕方(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='192b9bdd22ab9ed4d12e236c78afcb9a393ec15f71bbf5dc987d54727823bcbf'
)

デバッグモード Debug Mode

もしもappが準備を始めた後(after the app has begun setting up)で変更されると整合性を保てない振る舞いをするかもしれないため、DEBUGの設定値は特別です。デバッグモードを信頼して設定できるためには、flaskコマンドに--debugオプションを使います。flask runはデバッグモードでは標準でインタラクティブなデバッガと再読み込み機能(reloader)を使うでしょう。 The :data:`DEBUG` config value is special because it may behave inconsistently if changed after the app has begun setting up. In order to set debug mode reliably, use the ``--debug`` option on the ``flask`` command.``flask run`` will use the interactive debugger and reloader by default in debug mode.

$ flask --app hello --debug run

上記のようにオプションを使用することを推奨します。ENVDEBUGをconfigまたはコードの中で設定することは可能ですが、そのようにはしないことを強く勧めます。configまたはコードの中で設定した値はflaskコマンドでは早い段階で読み取ることができず、そしていくつかのシステムまたはFlask拡張は、それらが読み取られるより前の値で既に設定を済ませてしまっているかもしれません。 Using the option is recommended. While it is possible to set :data:`DEBUG` in your config or code, this is strongly discouraged. It 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を走らせるかを指定します。env属性がこの設定キーに対応付けられます(訳注:app.config['ENV']のようにもapp.envのようにもアクセスできます)。 What environment the app is running in. The :attr:`~flask.Flask.env` attribute maps to this config key.

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

バージョン 2.2 で非推奨: Flask 2.3では削除されるでしょう。--debug を代わりに使ってください。

Changelog

バージョン 1.0 で追加.

DEBUG

デバッグモードを有効にするかどうかを指定します。flask runを使用して開発サーバを開始するときは、捕捉されない例外はインタラクティブなデバッガで表示され、コードが変更されたときは再読み込みされるようになります。debug属性がこの設定キーに対応付けられます(訳注:app.config['DEBUG']のようにもapp.debugのようにもアクセスできます)。これは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 set with the ``FLASK_DEBUG`` environment variable. It may not behave as expected if set in code.

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

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

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のエラーハンドラで処理させる代わりに、発生させ直します(re-raise)。設定されていない場合、これは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``

TRAP_HTTP_EXCEPTIONS

もしもHTTPException-タイプの例外に対する処理(handler)がない場合、単純なエラーレスポンスとして返す代わりに、インタラクティブなデバッガで処理できるように、その例外を発生させ直します(re-raise)。 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)長いbytesまたはstrにするべきです。例えば、以下のコマンドの出力結果を自分の設定にコピーします: 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 ``bytes`` or ``str``. For example, copy the output of this to your config::

$ python -c 'import secrets; print(secrets.token_hex())'
'192b9bdd22ab9ed4d12e236c78afcb9a393ec15f71bbf5dc987d54727823bcbf'

質問を投稿するときやコードをコミットするときは、この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 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.

もしNoneであれば、send_fileはブラウザに、普通であれば好ましい、conditional requestをtimed cacheの代わりに使うよう伝えます(訳注: HTTPレスポンスのヘッダで「Cache-Control」を「no-cache」にして、conditional cachingを優先する指示をするようです。MDNのCache-Control > Requiring revalidation参照)(訳注: 原文では「send_file tells the browser to use conditional requests will be used instead of a timed cache ...」とあるが、「flask.Flask.send_file_max_age_default」の説明を見ると、おそらく「will be used」が余分)。 If ``None``, ``send_file`` tells the browser to use conditional requests will be used instead of a timed cache, which is usually preferable.

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

SERVER_NAME

どのホストとポートを使用するかアプリケーションに知らせます。サブドメインの経路(route)とのマッチングのサポートに必要になります。 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の仕様であるPEP3333の「environ Variable」を参照)。 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 :doc:`/patterns/appdispatch` 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文字を含むでしょう。これはテンプレートの中でJSONをJavaScriptへ変換するときにセキュリティに影響するので、典型的には有効にするべきです。 Serialize objects to ASCII-encoded JSON. If this is disabled, the JSON returned from ``jsonify`` will contain Unicode characters. This has security implications when rendering the JSON into JavaScript in templates, and should typically remain enabled.

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

バージョン 2.2 で非推奨: Flask 2.3では削除されるでしょう。app.json.ensure_ascii を代わりに設定してください。

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``

バージョン 2.2 で非推奨: Flask 2.3では削除されるでしょう。app.json.sort_keys を代わりに設定してください。

JSONIFY_PRETTYPRINT_REGULAR

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

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

バージョン 2.2 で非推奨: Flask 2.3では削除されるでしょう。app.json.compat を代わりに設定してください。

JSONIFY_MIMETYPE

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

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

バージョン 2.2 で非推奨: Flask 2.3では削除されるでしょう。app.json.mimetype を代わりに設定してください。

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.

バージョン 2.2 で変更: PRESERVE_CONTEXT_ON_EXCEPTION は削除されました。

バージョン 2.2 で変更: JSON_AS_ASCIIJSON_SORT_KEYSJSONIFY_MIMETYPE、そして JSONIFY_PRETTYPRINT_REGULAR はFlask 2.3で削除されるでしょう。標準の app.json プロバイダーが同一の属性を代わりに持ちます。

バージョン 2.2 で変更: ENV はFlask 2.3で削除されるでしょう。--debug を代わりに使ってください。

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

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

もし設定を別のファイルに格納出来たら、設定の読み取りはもっと便利になり、実際のアプリケーションのパッケージの外側に置ければ理想的です。特定の展開方法(specific deployment)では、自分のアプリケーションを展開(deploy)し、それから展開されたアプリケーションとは別のところで設定できます。 Configuration becomes more useful if you can store it in a separate file, ideally located outside the actual application package. You can deploy your application, then separately configure it for the specific deployment.

よくあるパターンは以下のとおりです: 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環境変数が指し示すファイルの内容を使って値を上書きします。この環境変数は、サーバを開始する前にシェルの中で設定できます: 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 in the shell before starting the server:

$ export YOURAPPLICATION_SETTINGS=/path/to/settings.cfg
$ flask run
 * Running on http://127.0.0.1:5000/

設定ファイルそれ自身は実際には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
SECRET_KEY = '192b9bdd22ab9ed4d12e236c78afcb9a393ec15f71bbf5dc987d54727823bcbf'

設定の読み込みは確実に早い段階で行ってください、そうすれば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 Data Files) Configuring from Data Files

from_file()を使って自分で選んだ形式のファイルから設定を読み込むこともできます。例えばTOMLファイルから読み取るには以下のようにします: It is also possible to load configuration from a file in a format of your choice using :meth:`~flask.Config.from_file`. For example to load from a TOML file:

import toml
app.config.from_file("config.toml", load=toml.load)

またはJSONファイルからは以下のようにします: Or from a JSON file:

import json
app.config.from_file("config.json", load=json.load)

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

環境変数を使用して設定ファイルを指し示すことに加えて、環境(environment)から直接設定値を制御することが便利(もしくは必要)なことがあるかもしれません。from_prefixed_env()を使って、特定の接頭辞(prefix)を使った全ての環境変数の文字列を設定に読み込むよう、Flaskに指示出来ます。 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. Flask can be instructed to load all environment variables starting with a specific prefix into the config using :meth:`~flask.Config.from_prefixed_env`.

環境変数は、サーバを開始する前にシェルの中で設定できます: Environment variables can be set in the shell before starting the server:

$ export FLASK_SECRET_KEY="5f352379324c22463451387a0aec5d2f"
$ export FLASK_MAIL_ENABLED=false
$ flask run
 * Running on http://127.0.0.1:5000/

変数はそれから、環境変数から接頭辞(prefix)を除いた名前と同じキーを使って、config経由で読み込みとアクセスが可能です。 The variables can then be loaded and accessed via the config with a key equal to the environment variable name without the prefix i.e.

app.config.from_prefixed_env()
app.config["SECRET_KEY"]  # Is "5f352379324c22463451387a0aec5d2f"

接頭辞(prefix)は標準ではFLASK_です。これはfrom_prefixed_env()prefix引数をとおして設定可能です。 The prefix is ``FLASK_`` by default. This is configurable via the ``prefix`` argument of :meth:`~flask.Config.from_prefixed_env`.

値は、文字列よりも具体的なタイプへの変換を試すために解析(parse)されます。標準設定ではjson.loads()が使われるため、listおよびdictを含む、どのような正当なJSONの値も利用可能です。これはfrom_prefixed_env()loads引数を通して設定可能です。 Values will be parsed to attempt to convert them to a more specific type than strings. By default :func:`json.loads` is used, so any valid JSON value is possible, including lists and dicts. This is configurable via the ``loads`` argument of :meth:`~flask.Config.from_prefixed_env`.

標準設定のJSON解析処理を使ってboolean値を加えるときは、小文字の「true」と「false」だけが正当な値になります。Pythonでは空ではない文字列はすべてTrueとみなされることは覚えておいてください。 When adding a boolean value with the default JSON parsing, only "true" and "false", lowercase, are valid values. Keep in mind that any non-empty string is considered ``True`` by Python.

2連続のアンダースコア(「__」)を使ってキーを分けることで、入れ子にされたdictionaryの中のキーを設定可能です。親のdictにはなく入れ子の途中にあるどのキーも空のdictに初期化されます。 It is possible to set keys in nested dictionaries by separating the keys with double underscore (``__``). Any intermediate keys that don't exist on the parent dict will be initialized to an empty dict.

$ export FLASK_MYAPI__credentials__username=user123
app.config["MYAPI"]["credentials"]["username"]  # Is "user123"

Windowsでは、環境変数のキーは常に大文字であり、従って上記の例は最終的にはMYAPI__CREDENTIALS__USERNAMEになります。 On Windows, environment variable keys are always uppercase, therefore the above example would end up as ``MYAPI__CREDENTIALS__USERNAME``.

複数の統合(merging)やWindowsでの大文字小文字の区別のサポートを含む、さらなる設定読み込みの目玉機能は、Dynaconfのような、Flaskへの統合を含んだ、専用のライブラリを試してください。 For even more config loading features, including merging and case-insensitive Windows support, try a dedicated library such as Dynaconf_, which includes integration with Flask.

設定のベストプラクティス 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.

  3. init_appを呼んだ時にFlask拡張が設定へアクセスできるように、かなり早い段階で設定を読み込むことを確実にしてくだささい。 Make sure to load the configuration very early on, so that extensions can access the configuration when calling ``init_app``.

開発環境/本番環境 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):
    TESTING = False

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

class DevelopmentConfig(Config):
    DATABASE_URI = "sqlite:////tmp/foo.db"

class TestingConfig(Config):
    DATABASE_URI = 'sqlite:///:memory:'
    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."""
    TESTING = False
    DB_SERVER = '192.168.1.56'

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

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

class DevelopmentConfig(Config):
    DB_SERVER = 'localhost'

class TestingConfig(Config):
    DB_SERVER = 'localhost'
    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のようなツールを本番環境で使用します。 Use a tool like `fabric`_ to push code and configuration separately to the production server(s).

インスタンスフォルダ 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/pythonX.Y/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()