Shellを使った作業 Working with the Shell

Changelog

バージョン 0.3 で追加.

皆がPythonを愛する理由の一つは、インタラクティブなshellです。それは基本的にPythonコマンドをリアルタイムで実行し即座に結果を取り戻すことを可能にします。(Shellを利用するために)前もって特別な準備をする必要はないため、Flask自体はインタラクティブなshellを伴っているわけではなく、(shellを使うには)自分のアプリケーションをただimportして、遊んでみてください。 One of the reasons everybody loves Python is the interactive shell. It basically allows you to execute Python commands in real time and immediately get results back. Flask itself does not come with an interactive shell, because it does not require any specific setup upfront, just import your application and start playing around.

しかしながらshellでの遊びをより楽しい経験にするための、便利なヘルパーがいくつか存在します。インタラクティブなコンソールでのセッションで重要な問題は、ブラウザが行うようにリクエストを引き起こしてはいないことで、それはg, requestなどが利用できないことを意味します。しかしあなたがテストしたいコードはそれら(g, requestなど)に依存しているものかもしれませんので、それではどうすればよいでしょうか? There are however some handy helpers to make playing around in the shell a more pleasant experience. The main issue with interactive console sessions is that you're not triggering a request like a browser does which means that :data:`~flask.g`, :data:`~flask.request` and others are not available. But the code you want to test might depend on them, so what can you do?

これはいくつかのヘルパー関数が便利な場所です。しかしながら、それらの関数はインタラクティブなshellで使用するためだけではなく、ユニットテストおよび偽装されたrequest contextを要求するその他の状況のためにもあるということを覚えていてください。 This is where some helper functions come in handy. Keep in mind however that these functions are not only there for interactive shell usage, but also for unit testing and other situations that require a faked request context.

概して、まずはドキュメントのリクエストのコンテキスト(The Request Context)の章を読んでおくことが推奨されます。 Generally it's recommended that you read the :ref:`request-context` chapter of the documentation first.

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

Flask 0.11から、shellを使って作業するための推奨されるやり方は、(shellを使って作業するために)多くのことを自動的に行うflask shellコマンドです。例えば読み込まれたapplication contextを使ってshellが自動的に初期化されます。 Starting with Flask 0.11 the recommended way to work with the shell is the ``flask shell`` command which does a lot of this automatically for you. For instance the shell is automatically initialized with a loaded application context.

さらなる情報はコマンドライン・インタフェースを確認してください。 For more information see :ref:`cli`.

リクエストのコンテキストの作成(Creating a Request Context) Creating a Request Context

適切なリクエストのcontextをshellから作成する最も簡単な方法は、RequestContextを作成するtest_request_contextメソッドを使用することです: The easiest way to create a proper request context from the shell is by using the :attr:`~flask.Flask.test_request_context` method which creates us a :class:`~flask.ctx.RequestContext`:

>>> ctx = app.test_request_context()

普通は(訳注: インタラクティブなshell以外の主な状況では)、このリクエストのオブジェクトを有効(active)にするためにwith文を使用するでしょうが、shellの中では手作業でpush()メソッドとpop()メソッドを使用する方が容易です: Normally you would use the ``with`` statement to make this request object active, but in the shell it's easier to use the :meth:`~flask.ctx.RequestContext.push` and :meth:`~flask.ctx.RequestContext.pop` methods by hand:

>>> ctx.push()

その点(上記のpushを実行した箇所)より後では、popを呼ぶまでは、リクエストのオブジェクトを使って作業できます。 From that point onwards you can work with the request object until you call `pop`:

>>> ctx.pop()

リクエスト前後の処理の起動(Firing Before/After Request) Firing Before/After Request

リクエストのcontextを作成するだけでは、普通は(訳注: インタラクティブなshell以外の主な状況では)リクエストの前に走るコードをまだ走らせていません。これは、もしリクエストの前のcallbackでデータベースに接続している場合にはデータベースが使えなくなったり、そのときのユーザ(current user)がgオブジェクトなどに格納されなくなったりするなどの結果を招くかもしれません。 By just creating a request context, you still don't have run the code that is normally run before a request. This might result in your database being unavailable if you are connecting to the database in a before-request callback or the current user not being stored on the :data:`~flask.g` object etc.

しかしながら、これはあなた自身によって簡単に実施できます。preprocess_request()を呼ぶだけです: This however can easily be done yourself. Just call :meth:`~flask.Flask.preprocess_request`:

>>> ctx = app.test_request_context()
>>> ctx.push()
>>> app.preprocess_request()

preprocess_request()関数はレスポンスのオブジェクトを返すかもしれず、その場合には単に無視することを覚えておいてください。 Keep in mind that the :meth:`~flask.Flask.preprocess_request` function might return a response object, in that case just ignore it.

リクエストを終わらせるには、終わらせる前にリクエストの後処理関数(the after request functions)(process_response()によって引き起こされます)がレスポンスのオブジェクトを操作するように、少し工夫が必要です: To shutdown a request, you need to trick a bit before the after request functions (triggered by :meth:`~flask.Flask.process_response`) operate on a response object:

>>> app.process_response(app.response_class())
<Response 0 bytes [200 OK]>
>>> ctx.pop()

teardown_request()として登録された関数は、contextがpopされるとき自動的に呼び出されます。従って、これはリクエストのcontextで必要とされていたリソース(例えばデータベース接続)を自動的に取り壊すには完璧な場所です。 The functions registered as :meth:`~flask.Flask.teardown_request` are automatically called when the context is popped. So this is the perfect place to automatically tear down resources that were needed by the request context (such as database connections).

Shellでの経験のさらなる改善 Further Improving the Shell Experience

もしshellの中で実験するというアイデアが気に入った場合、自分のインタラクティブなセッションの中にスターimport(訳注: 「*」を使ってモジュール内の関数など一式をまとめてimportすること)をしたくなるものを持ったモジュールを独自に作成してください。そこでは、例えばデータベースの初期化やテーブルの消去などのような、ありがちなものを手助けするメソッドをさらにいくつか定義もできます。 If you like the idea of experimenting in a shell, create yourself a module with stuff you want to star import into your interactive session. There you could also define some more helper methods for common things such as initializing the database, dropping tables etc.

それらをただ(shelltoolsのような)モジュールの中へ押し入れ、そこからimportします: Just put them into a module (like `shelltools`) and import from there:

>>> from shelltools import *