アプリケーションの用意(Application Setup) Application Setup

FlaskアプリケーションはFlaskクラスのインスタンスです。例えば設定やURLなど、アプリケーションに関してはすべて、このクラスを使って登録します。 A Flask application is an instance of the :class:`Flask` class. Everything about the application, such as configuration and URLs, will be registered with this class.

最も直観的なFlaskアプリケーションの作成方法は、コードの最上部にグローバルな(モジュールのトップレベルとほぼ同じ意味合いで、Pythonで変数などのスコープや名前解決でLEGBルール(Local, Enclosing, Global, Built-in)と呼ばれるもののGlobalにあたるもの):class:Flaskインスタンスを直接作成することで、前ページの例「Hello, World!」のようなやり方です。これは場合によってはシンプルで便利ですが、プロジェクトが成長すると何かしら扱いにくい問題を引き起こす可能性があります。 The most straightforward way to create a Flask application is to create a global :class:`Flask` instance directly at the top of your code, like how the "Hello, World!" example did on the previous page. While this is simple and useful in some cases, it can cause some tricky issues as the project grows.

Flaskインスタンスをグローバルに作成する代わりに、関数の内側で作成するようにします。この関数はアプリケーション製造工場(application factory)として知られています。アプリケーションが必要とするあらゆる設定、登録、用意などは、この関数の内側で起こり、それからアプリケーションが返されます(Flaskクラスのインスタンスがfactory関数から返されます)。 Instead of creating a :class:`Flask` instance globally, you will create it inside a function. This function is known as the *application factory*. Any configuration, registration, and other setup the application needs will happen inside the function, then the application will be returned.

アプリケーション製造工場(The Application Factory) The Application Factory

それではコーディングを開始するときです!flaskrディレクトリを作成し、__init__.pyファイルを追加します。この__init__.pyは2つの務めを担います: それはapplication factoryを含むことと、Pythonへflaskrディレクトリをpackageとして扱うように伝えることです。 It's time to start coding! Create the ``flaskr`` directory and add the ``__init__.py`` file. The ``__init__.py`` serves double duty: it will contain the application factory, and it tells Python that the ``flaskr`` directory should be treated as a package.

$ mkdir flaskr
flaskr/__init__.py
import os

from flask import Flask


def create_app(test_config=None):
    # create and configure the app
    app = Flask(__name__, instance_relative_config=True)
    app.config.from_mapping(
        SECRET_KEY='dev',
        DATABASE=os.path.join(app.instance_path, 'flaskr.sqlite'),
    )

    if test_config is None:
        # load the instance config, if it exists, when not testing
        app.config.from_pyfile('config.py', silent=True)
    else:
        # load the test config if passed in
        app.config.from_mapping(test_config)

    # ensure the instance folder exists
    try:
        os.makedirs(app.instance_path)
    except OSError:
        pass

    # a simple page that says hello
    @app.route('/hello')
    def hello():
        return 'Hello, World!'

    return app

create_appはapplication factoryの関数です。このチュートリアルで後程この関数に追加していきますが、既に多くのことを(create_appは)果しています。 ``create_app`` is the application factory function. You'll add to it later in the tutorial, but it already does a lot.

  1. app = Flask(__name__, instance_relative_config=True)Flaskインスタンスを作成します。 ``app = Flask(__name__, instance_relative_config=True)`` creates the :class:`Flask` instance.

    • __name__は、この時点でのPythonのmodule名です。appは、いくつかpathを用意するために、appがどの場所にあるか知る必要があり、__name__はそれを伝えるための便利なやり方です。 ``__name__`` is the name of the current Python module. The app needs to know where it's located to set up some paths, and ``__name__`` is a convenient way to tell it that.

    • instance_relative_config=Trueは、設定ファイル(の場所)がインスタンスフォルダから相対的に示されることを、appへ伝えます。インスタンスフォルダはflaskrパッケージの外側に位置し、秘密情報の設定やデータベースのファイルなど、バージョン管理へコミットするべきではないローカルのデータを保持することができます。 ``instance_relative_config=True`` tells the app that configuration files are relative to the :ref:`instance folder <instance-folders>`. The instance folder is located outside the ``flaskr`` package and can hold local data that shouldn't be committed to version control, such as configuration secrets and the database file.

  2. app.config.from_mapping()は、appが使用する標準設定をいくつか設定します: :meth:`app.config.from_mapping() <Config.from_mapping>` sets some default configuration that the app will use:

    • SECRET_KEYは、データを安全に保つためにFlaskとFlask拡張によって使用されます。開発中には便利な値を提供するために、ここでは'dev'に設定されていますが、デプロイ(訳注:本番環境などへの移行)をするときには無作為な値(random value)で上書きするべきです。 :data:`SECRET_KEY` is used by Flask and extensions to keep data safe. It's set to ``'dev'`` to provide a convenient value during development, but it should be overridden with a random value when deploying.

    • DATABASEはSQLiteデータベースファイルが保存されるパスです。それは、Flaskがインスタンスフォルダに選んだパスである、app.instance_pathの下になります。次のセクションでデータベースについてさらに学習します。 ``DATABASE`` is the path where the SQLite database file will be saved. It's under :attr:`app.instance_path <Flask.instance_path>`, which is the path that Flask has chosen for the instance folder. You'll learn more about the database in the next section.

  3. app.config.from_pyfile()は、もしインスタンスフォルダにconfig.pyファイルがあれば、値をそこから取り出して、標準設定を上書きします。例えば、デプロイの時には、本当のSECRET_KEYを設定するために使用できます。 :meth:`app.config.from_pyfile() <Config.from_pyfile>` overrides the default configuration with values taken from the ``config.py`` file in the instance folder if it exists. For example, when deploying, this can be used to set a real ``SECRET_KEY``.

    • test_configもfactoryに渡すことが可能で、インスタンス設定の代わりに使用されます。これは、このチュートリアルの後の方で書くテストで、開発時に設定してきたあらゆる値から独立して設定できるようにするためです。 ``test_config`` can also be passed to the factory, and will be used instead of the instance configuration. This is so the tests you'll write later in the tutorial can be configured independently of any development values you have configured.

  4. os.makedirs()app.instance_pathが確実に存在するようにします。Flaskはインスタンスフォルダを自動的には作成しませんが、このプロジェクトではそこにSQLiteデータベースファイルを作成するためにインスタンスフォルダが作成されている必要があります。 :func:`os.makedirs` ensures that :attr:`app.instance_path <Flask.instance_path>` exists. Flask doesn't create the instance folder automatically, but it needs to be created because your project will create the SQLite database file there.

  5. @app.route()はチュートリアルの残りの部分へ進む前に、アプリケーションが機能していることを確かめるための簡易な経路(route)を作成します。その経路は、URLの/helloと、この場合は文字列'Hello, World!'というレスポンスを返す関数とを、結び付けます。 :meth:`@app.route() <Flask.route>` creates a simple route so you can see the application working before getting into the rest of the tutorial. It creates a connection between the URL ``/hello`` and a function that returns a response, the string ``'Hello, World!'`` in this case.

アプリケーションの実行 Run The Application

この時点で、flaskコマンドを使ってアプリケーションを実行できます。端末から、アプリケーションがどこで見つかるかを伝え、それから開発モードでそれを実行するよう、Flaskへ伝えます。flaskrパッケージではなく、トップレベルのflask-tutorialディレクトリにまだいるべきであることを忘れないでください。 Now you can run your application using the ``flask`` command. From the terminal, tell Flask where to find your application, then run it in development mode. Remember, you should still be in the top-level ``flask-tutorial`` directory, not the ``flaskr`` package.

開発モードは、ページが例外を起こしたときにはインタラクティブなデバッガを表示し、コードを変更したときにはサーバを再起動します。チュートリアルを続けるとき、Flaskを実行させたままにしながら、ブラウザのページを再読み込みするだけで済むようにします。 Development mode shows an interactive debugger whenever a page raises an exception, and restarts the server whenever you make changes to the code. You can leave it running and just reload the browser page as you follow the tutorial.

LinuxおよびMac向け: For Linux and Mac:

$ export FLASK_APP=flaskr
$ export FLASK_ENV=development
$ flask run

Windowsのcmdでは、exportの代わりにsetを使用します: For Windows cmd, use ``set`` instead of ``export``:

> set FLASK_APP=flaskr
> set FLASK_ENV=development
> flask run

WindowsのPowerShellでは、exportの代わりに$env:を使用します: For Windows PowerShell, use ``$env:`` instead of ``export``:

> $env:FLASK_APP = "flaskr"
> $env:FLASK_ENV = "development"
> flask run

以下と似たような出力が見られるでしょう: You'll see output similar to this:

* Serving Flask app "flaskr"
* Environment: development
* Debug mode: on
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
* Restarting with stat
* Debugger is active!
* Debugger PIN: 855-212-761

http://127.0.0.1:5000/helloをブラウザで訪れると「Hello, World!」メッセージを見られるはずです。おめでとうございます、この時点で自分のFlask webアプリケーションを実行中です! Visit http://127.0.0.1:5000/hello in a browser and you should see the "Hello, World!" message. Congratulations, you're now running your Flask web application!

データベースの定義とアクセスへ続きます。 Continue to :doc:`database`.