============================================== リクエストオブジェクトとレスポンスオブジェクト ============================================== :revision-up-to: 17812 (1.4) .. module:: django.http :synopsis: HTTP のリクエストとレスポンスを扱うためのクラスです。 簡単な概要 ========== Django は、システム全体にわたって、リクエストとレスポンスオブジェクトを使っ て処理状態を受け渡します。 あるページへのリクエストを受け取ると、Django は :class:`~django.http.HttpRequest` オブジェクトを生成します。このオブジェク トにはリクエストのメタデータが入っています。次に Django は適切なビューをロー ドして、 :class:`~django.http.HttpRequest` をビュー関数の最初の引数に渡しま す。各ビューは :class:`~django.http.HttpResponse` オブジェクトを返さねばな りません。 このドキュメントでは :class:`~django.http.HttpRequest` および :class:`~django.http.HttpResponse` オブジェクトの API について説明します。 HttpRequest オブジェクト ======================== .. class:: HttpRequest .. _httprequest-attributes: 属性 ---- ``session`` 以外の属性は全て読み出し専用です。 .. attribute:: HttpRequest.body .. versionchanged:: 1.4 .. Before Django 1.4, ``HttpRequest.body`` was named ``HttpRequest.raw_post_data``. Django 1.4 以前では、``HttpRequest.body`` は ``HttpRequest.raw_post_data`` でした. .. The raw HTTP request body as a byte string. This is useful for processing data in different ways than conventional HTML forms: binary images, XML payload etc. For processing conventional form data, use ``HttpRequest.POST``. 生の HTTP リクエストのバイト文字列です。これは従来の HTML フォームと 異なる、バイナリ画像や XML ペイロードのデータを処理するのに便利です。 従来のフォームのデータを処理するためには ``HttpRequest.POST`` を 使って下さい。 .. versionadded:: 1.3 .. You can also read from an HttpRequest using a file-like interface. See :meth:`HttpRequest.read()`. HttpRequest をファイルのようなインターフェースで読むことも出来ます。 後述の :meth:`HttpRequest.read()` も参照して下さい。 .. attribute:: HttpRequest.path リクエストしているページのフルパスを表す、ドメインを含まない文字列です。 例: ``"/music/bands/the_beatles/"`` .. attribute:: HttpRequest.path_info .. Under some Web server configurations, the portion of the URL after the host name is split up into a script prefix portion and a path info portion (this happens, for example, when using the ``django.root`` option with the :doc:`modpython handler from Apache `). The ``path_info`` attribute always contains the path info portion of the path, no matter what Web server is being used. Using this instead of attr:`~HttpRequest.path` can make your code much easier to move between test and deployment servers. いくつかの Web サーバーの設定において、ホストネーム以降の URL の一部が スクリプトプレフィックスの部分と PATH_INFO の部分に分割されます。 ( 例えば、これが発生するのは、 ``django.root`` オプションを :doc:`Apache と mod_python で Django を動かす ` で使っている場合 ) ``path_info`` 属性には、どの Web サーバーが使われている かに関わらず、常にパスの PATH_INFO の部分が入ります。 :attr:`~HttpRequest.path` の代わりに使うことで、テストサーバーから本番 サーバーへの移行が簡単なコードにすることが出来ます。 .. For example, if the ``WSGIScriptAlias`` for your application is set to ``"/minfo"``, then ``path`` might be ``"/minfo/music/bands/the_beatles/"`` and ``path_info`` would be ``"/music/bands/the_beatles/"``. 例えば、もしアプリケーションの ``WSGIScriptAlias`` が ``"/minfo"`` に 設定されていた場合、 ``path`` は ``"/minfo/music/bands/the_beatles/"`` に ``path_info`` は ``"/music/bands/the_beatles/"`` になるでしょう。 .. attribute:: HttpRequest.method リクエストに使われた HTTP メソッドを表す文字列です。必ず大文字になります。 例:: if request.method == 'GET': do_something() elif request.method == 'POST': do_something_else() .. attribute:: HttpRequest.encoding 提出されたフォームデータのデコードに使われる、現在のエンコーディングを 表す文字列です (``None`` の場合もありますが、この場合は :setting:`DEFAULT_CHARSET` を使います)。この属性を変更すれば、フォーム データにアクセスする際に使われるエンコーディングを指定できます。一度エ ンコーディングを変更すると、変更後に (``GET`` や ``POST`` の) 属性への アクセスはすべて新しい ``encoding`` の値に従って行われます。フォームデー タが :setting:`DEFAULT_CHARSET` 以外の特定のエンコーディングと分かって いる場合に便利です。 .. attribute:: HttpRequest.GET 全ての HTTP GET パラメタが入った辞書ライクなオブジェクトです。後述の :class:`QueryDict` も参照してください。 .. attribute:: HttpRequest.POST 全ての HTTP POST パラメタが入った辞書ライクなオブジェクトです。後述の :class:`QueryDict` も参照してください。 フォームを POST HTTP メソッドで要求し、その際に何らフォームデータを伴わ ないような場合には、リクエストが POST で送られていながらも ``POST`` 辞 書が空になることがあります。従って、リクエストが POST メソッドであるか どうかを調べるために ``if request.POST`` を使うべきではありません。代わ りに ``if request.method == "POST"`` を使ってください (上参照)。 ``POST`` にはファイルアップロードに関する情報は *入っていない* ので注意 してください。 ``FILES`` を参照してください。 .. attribute:: HttpRequest.REQUEST 便宜的な辞書オブジェクトで、 ``POST`` パラメタをまず検索してから、次に ``GET`` パラメタを検索します。 PHP の ``$_REQUEST`` にインスパイアされ た機能です。 例えば、 ``GET = {"name": "john"}`` で ``POST = {"age": '34'}`` の場合、 ``REQUEST["name"]`` は ``"john"`` になり、 ``REQUEST["age"]`` は ``"34"`` になります。 通常は ``GET`` および ``POST`` を使うように強く勧めます。その方が明示的 だからです。 .. attribute:: HttpRequest.COOKIES 全てのクッキーが入った標準の Python 辞書オブジェクトです。キーと値は文 字列です。 .. attribute:: HttpRequest.FILES アップロードされた全てのファイルが入っている辞書ライクオブジェクトです。 ``FILES`` の各キーは ```` の ``name`` に対応しています。 ``FILES`` の各値は後述の :class:`UploadedFile` オブジ ェクトです. 詳しくは :doc:`/topics/files` を参照してください。 ``FILES`` にデータが入るのは、リクエストが ``POST`` であり、かつリクエ ストをポストした ``
`` に ``enctype="multipart/form-data`` がある 場合だけです。それ以外の場合、 ``FILES`` は空の辞書ライクオブジェクトに なります。 .. attribute:: HttpRequest.META 標準の Python 辞書オブジェクトで、利用できる全ての HTTP ヘッダが入って います。利用可能なヘッダはクライアントとサーバごとに違いますが、例えば 以下のようなヘッダを利用できます: .. * ``CONTENT_LENGTH`` -- the length of the request body (as a string). * ``CONTENT_TYPE`` -- the MIME type of the request body. * ``HTTP_ACCEPT_ENCODING`` -- Acceptable encodings for the response. * ``HTTP_ACCEPT_LANGUAGE`` -- Acceptable languages for the response. * ``HTTP_HOST`` -- The HTTP Host header sent by the client. * ``HTTP_REFERER`` -- The referring page, if any. * ``HTTP_USER_AGENT`` -- The client's user-agent string. * ``QUERY_STRING`` -- The query string, as a single (unparsed) string. * ``REMOTE_ADDR`` -- The IP address of the client. * ``REMOTE_HOST`` -- The hostname of the client. * ``REMOTE_USER`` -- The user authenticated by the Web server, if any. * ``REQUEST_METHOD`` -- A string such as ``"GET"`` or ``"POST"``. * ``SERVER_NAME`` -- The hostname of the server. * ``SERVER_PORT`` -- The port of the server (as a string). * ``CONTENT_LENGTH`` -- リクエストのボディの長さ(文字列)です。 * ``CONTENT_TYPE`` -- リクエストのボディの MIME タイプです。 * ``HTTP_ACCEPT_ENCODING`` -- レスポンスとして利用可能な文字コードです。 * ``HTTP_ACCEPT_LANGUAGE`` -- レスポンスとして利用可能な言語です。 * ``HTTP_HOST`` -- クライアントによって送信された HTTP Host ヘッダです。 * ``HTTP_REFERER`` -- リクエスト対象のページを参照しているページが ある場合、そのページの URL です。 * ``HTTP_USER_AGENT`` -- クライアントのユーザエージェントの文字列です。 * ``QUERY_STRING`` -- パース前の単一のクエリ文字列です。 * ``REMOTE_ADDR`` -- クライアントの IP アドレスです。 * ``REMOTE_HOST`` -- クライアントのホスト名です。 * ``REMOTE_USER`` -- Web サーバーによって認証されたユーザがある場合、 そのユーザです。 * ``REQUEST_METHOD`` -- ``"GET"`` や ``"POST"`` のような文字列です。 * ``SERVER_NAME`` -- サーバのホスト名です。 * ``SERVER_PORT`` -- サーバのポート番号(文字列)です。 .. With the exception of ``CONTENT_LENGTH`` and ``CONTENT_TYPE``, as given above, any HTTP headers in the request are converted to ``META`` keys by converting all characters to uppercase, replacing any hyphens with underscores and adding an ``HTTP_`` prefix to the name. So, for example, a header called ``X-Bender`` would be mapped to the ``META`` key ``HTTP_X_BENDER``. ``CONTENT_LENGTH`` と ``CONTENT_TYPE`` の例外を含め、上に示されたように、 リクエストのどの HTTP ヘッダも、すべての文字を大文字に変換し、すべての ハイフンをアンダーバーに置き換え、 名前に ``HTTP_`` のプレフィックスを 付加して ``META`` のキーに変換されます。よって、例えば、 ``X-Bender`` というヘッダは ``META`` で ``HTTP_X_BENDER`` のキーに割り当てられます。 .. attribute:: HttpRequest.user 現在ログインしているユーザを表す ``django.models.auth.models.User`` オブ ジェクトです。ユーザが現在ログインしていない場合には、 ``user`` は ``django.contrib.auth.models.AnonymousUser`` のインスタンスになります。 ``is_authenticated()`` を使うと、これら二種類のユーザを区別できます:: if request.user.is_authenticated(): # Do something for logged-in users. else: # Do something for anonymous users. ``user`` を利用できるのは、 インストールした Django で ``AuthenticationMiddleware`` を有効にした場合だけです。詳しくは :doc:`/topics/auth` を参照してください。 .. attribute:: HttpRequest.session 読み書き可能な辞書ライクオブジェクトで、現在のセッションを表現しています。 この辞書はインストールされている Django でセッションが有効な場合にのみ 利用できます。 詳しくは :doc:`セッションのドキュメント ` を 参照してください。 .. attribute:: HttpRequest.urlconf Django 自体はこの属性を設定しませんが、他のコード(自作のミドルウェアな ど)でこの属性を設定した場合、Djangoはその値を :setting:`ROOT_URLCONF` の代わりにルート URLconf モジュール名として使います。 詳しくは 「 :ref:`how-django-processes-a-request` 」を参照してください。 メソッド -------- .. method:: HttpRequest.get_host() .. Returns the originating host of the request using information from the ``HTTP_X_FORWARDED_HOST`` (if :setting:`USE_X_FORWARDED_HOST` is enabled) and ``HTTP_HOST`` headers, in that order. If they don't provide a value, the method uses a combination of ``SERVER_NAME`` and ``SERVER_PORT`` as detailed in :pep:`3333`. ``HTTP_X_FORWARDED_HOST`` ヘッダ(:setting:`USE_X_FORWARDED_HOST` が 有効化されている場合)と ``HTTP_HOST`` ヘッダを順に調べて、リクエストの 送信元を返します。クライアントがそれらの値を提供していない場合は :pep:`3333` に従って、``SERVER_NAME`` と ``SERVER_PORT`` の組み合わせを 返します。 .. Example: ``"127.0.0.1:8000"`` 例: ``"127.0.0.1:8000"`` .. .. note:: The :meth:`~HttpRequest.get_host()` method fails when the host is behind multiple proxies. One solution is to use middleware to rewrite the proxy headers, as in the following example:: .. note:: ホストが複数のプロキシを通しているとき、 :meth:`~HttpRequest.get_host()` は失敗します。一つの解決策は ロキシヘッダを書き換えるミドルウェアを利用することです。 以下に例を示します:: class MultipleProxyMiddleware(object): FORWARDED_FOR_FIELDS = [ 'HTTP_X_FORWARDED_FOR', 'HTTP_X_FORWARDED_HOST', 'HTTP_X_FORWARDED_SERVER', ] def process_request(self, request): """ Rewrites the proxy headers so that only the most recent proxy is used. """ for field in self.FORWARDED_FOR_FIELDS: if field in request.META: if ',' in request.META[field]: parts = request.META[field].split(',') request.META[field] = parts[-1].strip() .. This middleware should be positioned before any other middleware that relies on the value of :meth:`~HttpRequest.get_host()` -- for instance, :class:`~django.middleware.common.CommonMiddleware` or :class:`~django.middleware.csrf.CsrfViewMiddleware`. このミドルウェアは :meth:`~HttpRequest.get_host()` の値を利用する :class:`~django.middleware.common.CommonMiddleware` や :class:`~django.middleware.csrf.CsrfViewMiddleware` のような 他のミドルウェアの前に置かなければなりません。 .. method:: HttpRequest.get_full_path() ``path`` と、そのあとに続くクエリ文字列があれば返します。 例: ``"/music/bands/the_beatles/?print=true"`` .. method:: HttpRequest.build_absolute_uri(location) ``location`` の絶対 URI を計算して返します。引数 ``location`` を省略する と、 ``location`` の値として ``request.get_full_path()`` を使います。 ``location`` の値がすでに絶対 URI であれば、値を変更しません。そうでない 場合、リクエスト中のサーバに関する変数を使って URI を構築します。 例: ``"http://example.com/music/bands/the_beatles/?print=true"`` .. method:: HttpRequest.get_signed_cookie(key, default=RAISE_ERROR, salt='', max_age=None) .. versionadded:: 1.4 .. Returns a cookie value for a signed cookie, or raises a :class:`~django.core.signing.BadSignature` exception if the signature is no longer valid. If you provide the ``default`` argument the exception will be suppressed and that default value will be returned instead. 署名付きクッキーのクッキーの値を返すか、署名が有効でない場合は :class:`~django.core.signing.BadSignature` 例外を発生します。 ``default`` 引数を与えた場合は、例外は抑制され、代わりにデフォルトの 値が返されます。 .. The optional ``salt`` argument can be used to provide extra protection against brute force attacks on your secret key. If supplied, the ``max_age`` argument will be checked against the signed timestamp attached to the cookie value to ensure the cookie is not older than ``max_age`` seconds. オプションの ``salt`` 引数はシークレットキーへのブルートフォース攻撃に 対する追加の防御を与えるために利用されます。引数が与えられた場合、 ``max_age`` 引数は、 ``max_age`` 秒よりクッキーが古くないかを確認する ために、クッキーの署名されたタイムスタンプに対してチェックされます。 .. For example:: 例:: >>> request.get_signed_cookie('name') 'Tony' >>> request.get_signed_cookie('name', salt='name-salt') 'Tony' # assuming cookie was set using the same salt >>> request.get_signed_cookie('non-existing-cookie') ... KeyError: 'non-existing-cookie' >>> request.get_signed_cookie('non-existing-cookie', False) False >>> request.get_signed_cookie('cookie-that-was-tampered-with') ... BadSignature: ... >>> request.get_signed_cookie('name', max_age=60) ... SignatureExpired: Signature age 1677.3839159 > 60 seconds >>> request.get_signed_cookie('name', False, max_age=60) False .. See :doc:`cryptographic signing ` for more information. 詳細は :doc:`暗号による署名 ` を参照して下さい。 .. method:: HttpRequest.is_secure() リクエストがセキュアである、すなわち HTTPS を介したリクエストのときに ``True`` を返します。 .. method:: HttpRequest.is_ajax() リクエストが ``XMLHttpRequest`` である場合には ``True`` に設定されます。 リクエストが ``XMLHttpRequest`` であるかどうかは、 ``HTTP_X_REQUESTED_WITH`` ヘッダに文字列 ``XMLHttpRequest`` があるかどう かで判別します。このヘッダは、ほとんどのモダンな主要 JavaScript ライブ ラリでサポートされています。 ブラウザ側で XMLHttpRequest を呼び出す独自のコードを書いている場合、 ``is_ajax()`` を正しく機能させたいなら、 ``HTTP_X_REQUESTED_WITH`` ヘッ ダを適切に設定してください。 .. method:: HttpRequest.read(size=None) .. method:: HttpRequest.readline() .. method:: HttpRequest.readlines() .. method:: HttpRequest.xreadlines() .. method:: HttpRequest.__iter__() .. versionadded:: 1.3 .. Methods implementing a file-like interface for reading from an HttpRequest instance. This makes it possible to consume an incoming request in a streaming fashion. A common use-case would be to process a big XML payload with iterative parser without constructing a whole XML tree in memory. HTTPRequest のインスタンスからファイルのようなインターフェースで 読むメソッドです。このメソッドはやってくるリクエストをストリーミング のやり方で消費することを可能にします。一般的な利用事例は大きな XML ペイロードを、反復パーサでメモリ上にすべての XML ツリーを 構築することなく、処理することです。 .. Given this standard interface, an HttpRequest instance can be passed directly to an XML parser such as ElementTree:: この標準的なインターフェースを使って、直接 ElementTree のような XML パーサに HTTPRequest インスタンスを渡すことが出来ます:: import xml.etree.ElementTree as ET for element in ET.iterparse(request): process(element) UploadedFile オブジェクト ========================= .. class:: UploadedFile 属性 ---- .. attribute:: UploadedFile.name .. The name of the uploaded file. アップロードされたファイルの名前。 .. attribute:: UploadedFile.size .. The size, in bytes, of the uploaded file. バイト単位でのアップロードされたファイルのサイズ。 メソッド -------- .. method:: UploadedFile.chunks(chunk_size=None) .. Returns a generator that yields sequential chunks of data. データの連続したチャンクを生成するジェネレータを返します。 .. method:: UploadedFile.read(num_bytes=None) .. Read a number of bytes from the file. 引数のバイト数分ファイルを読みます。 QueryDict オブジェクト ====================== :class:`~django.http.HttpRequest` オブジェクト内では、 ``GET`` と ``POST`` 属性は :class:`django.http.QueryDict` のインスタンスです。 :class:`~django.http.QueryDict` は辞書ライクなクラスで、同じキーに対して複 数の値を取り得るようにカスタマイズされています。これは、 HTML のフォーム要 素には、例えば ``