PEP 333: Python Web Server Gateway Interface v1.0

PEP:333
Title:Python Web Server Gateway Interface v1.0
Version:$Revision:$
Last-Modified:$Date:$
Author:Phillip J. Eby <pje@telecommunity.com>
Discussions-To:Python Web-SIG <web-sig@python.org>
Status:Final
Type:Informational
Content-Type:text/x-rst
Created:07-Dec-2003
Post-History:07-Dec-2003, 08-Aug-2004, 20-Aug-2004, 27-Aug-2004, 27-Sep-2010
Replaced-By:3333

Preface

序文

Note: For an updated version of this spec that supports Python 3.x and includes community errata, addenda, and clarifications, please see PEP 3333 instead.

注意: Python 3.x をサポートし、コミュニティ正誤表、補遺、および明確化を 含むこの仕様のアップデートバージョンについては、代わりに PEP 3333 を見 てください。

Abstract

はじめに

This document specifies a proposed standard interface between web servers and Python web applications or frameworks, to promote web application portability across a variety of web servers.

この文書は、Web サーバーと Python Web アプリケーション/フレームワークの 間の標準インタフェースの詳細を提案するものである。この提案によって、様々 な Web サーバー間での Web アプリケーションの移植可能性が促進される。

Rationale and Goals

理由と目的

Python currently boasts a wide variety of web application frameworks, such as Zope, Quixote, Webware, SkunkWeb, PSO, and Twisted Web – to name just a few [1]. This wide variety of choices can be a problem for new Python users, because generally speaking, their choice of web framework will limit their choice of usable web servers, and vice versa.

Python には現在、いくつか例を挙げるだけでも、Zope、Quixote、Webware、 SkunkWeb、PSO、Twisted Web といった様々な Web アプリケーション・フレー ムワークが乱立している [1] 。このような幅広い選択肢は、Python を新たに 始める人にとって問題になる。なぜなら、一般に、Web フレームワークの選択 が使用可能な Web サーバーの選択を制限して、逆もまた同様であるからだ。

By contrast, although Java has just as many web application frameworks available, Java’s “servlet” API makes it possible for applications written with any Java web application framework to run in any web server that supports the servlet API.

対照的に、 Java では同様に多くの Web アプリケーション・フレームワークが あるにも関わらず、 Java “servelet” API があることで servelet API をサポー トする任意の Web サーバー上で任意の Java Web アプリケーション・フレーム ワークで書かれたアプリケーションを動かすことができる。

The availability and widespread use of such an API in web servers for Python – whether those servers are written in Python (e.g. Medusa), embed Python (e.g. mod_python), or invoke Python via a gateway protocol (e.g. CGI, FastCGI, etc.) – would separate choice of framework from choice of web server, freeing users to choose a pairing that suits them, while freeing framework and server developers to focus on their preferred area of specialization.

Python においても同様の API が提供され、普及すれば、 Web サーバーが Python で書かれているか (例えば Medusa)、埋め込み Python か (例えば mod_python)、またはゲートウェイプロトコル (例えば CGI、FastCGI など) か ら Python を呼び出すか、といったこととは関係なく、 Web サーバーの選択と フレームワークの選択を切り離し、ユーザは自由な組み合わせで Web サーバー とフレームワークを選ぶことができるようになるだろう。また、フレームワー クやサーバの開発者は、特徴を出したい領域に力を注ぐことができるようにな るだろう。

This PEP, therefore, proposes a simple and universal interface between web servers and web applications or frameworks: the Python Web Server Gateway Interface (WSGI).

そのため、この PEP では Web サーバーと Web アプリケーション/フレームワー クの間の、簡単で汎用的なインタフェースを提案する: Python Web Server Gateway Interface (WSGI) である。

But the mere existence of a WSGI spec does nothing to address the existing state of servers and frameworks for Python web applications. Server and framework authors and maintainers must actually implement WSGI for there to be any effect.

しかし、 WSGI 仕様があるだけでは、 Python Web アプリケーションのサーバ やフレームワークの現状の問題を解決することにはならない。それが何らかの 効果を発揮するためには、サーバとフレームワークの作者およびメンテナーが 実際に WSGI を実装する必要がある。

However, since no existing servers or frameworks support WSGI, there is little immediate reward for an author who implements WSGI support. Thus, WSGI must be easy to implement, so that an author’s initial investment in the interface can be reasonably low.

しかしながら、今のところ WSGI をサポートする既存のサーバもフレームワー クも存在しないので、 WSGI サポートを実装する作者に即時の報酬はほとんど ない。そのため、作者の初期投資が十分低くなるように、 WSGI は実装するの が簡単でなければならない (must) 。

Thus, simplicity of implementation on both the server and framework sides of the interface is absolutely critical to the utility of the WSGI interface, and is therefore the principal criterion for any design decisions.

したがって、サーバとフレームワークの 両方 でインタフェースの実装が簡 単であることが WSGI に関する実用性にとって絶対的に重要であり、そのため、 それがあらゆるデザイン決定のための主要な評価基準である。

Note, however, that simplicity of implementation for a framework author is not the same thing as ease of use for a web application author. WSGI presents an absolutely “no frills” interface to the framework author, because bells and whistles like response objects and cookie handling would just get in the way of existing frameworks’ handling of these issues. Again, the goal of WSGI is to facilitate easy interconnection of existing servers and applications or frameworks, not to create a new web framework.

しかしながら、フレームワーク作者のための実装の簡単さは、 Web アプリケー ション作者のための使いやすさと同じものではないことに注意すること。 WSGI は、フレームワーク作者に完全に「余計な飾りのない」インタフェースを 提示する。なぜなら、レスポンスオブジェクトやクッキーの処理のような付属 品は、既存のフレームワークがこれらの課題を取り扱うのを邪魔するものに過 ぎないからだ。繰り返すが、 WSGI の目標は既存のサーバとアプリケーション /フレームワーク間の連携を手助けすることであり、新しい Web フレームワー クを作ることではない。

Note also that this goal precludes WSGI from requiring anything that is not already available in deployed versions of Python. Therefore, new standard library modules are not proposed or required by this specification, and nothing in WSGI requires a Python version greater than 2.2.2. (It would be a good idea, however, for future versions of Python to include support for this interface in web servers provided by the standard library.)

また、この目標によって WSGI が Python の配布バージョンでまだ利用可能で ない何かを要求することが排除されるということに注意すること。したがって、 この仕様によって新しい標準のライブラリモジュールが提案されるわけではな いし、また必要とされることもない。そして、WSGI において Python 2.2.2 以 上のバージョンを必要としない。 (しかしながら、 Python の将来のバージョ ンで、標準のライブラリによって提供される Web サーバーにこのインタフェー スのサポートを含めるのは良いアイデアだろう。)

In addition to ease of implementation for existing and future frameworks and servers, it should also be easy to create request preprocessors, response postprocessors, and other WSGI-based “middleware” components that look like an application to their containing server, while acting as a server for their contained applications.

既存のまたは将来のフレームワークとサーバにとって実装が容易であることに 加えて、リクエストのプリプロセッサやレスポンスのポストプロセッサ、その 他の WSGI ベースの「ミドルウェア」コンポーネント(サーバに対してはアプ リケーションのように見える一方で、アプリケーションのためにはサーバとし て機能する)を作成するのも簡単であるべきである。

If middleware can be both simple and robust, and WSGI is widely available in servers and frameworks, it allows for the possibility of an entirely new kind of Python web application framework: one consisting of loosely-coupled WSGI middleware components. Indeed, existing framework authors may even choose to refactor their frameworks’ existing services to be provided in this way, becoming more like libraries used with WSGI, and less like monolithic frameworks. This would then allow application developers to choose “best-of-breed” components for specific functionality, rather than having to commit to all the pros and cons of a single framework.

もしミドルウェアが簡単でかつ強健であるなら、そして WSGI がサーバとフレー ムワークで広く利用可能であるなら、完全に新しい種類の Python Web アプリ ケーションフレームワークをもたらす可能性がある: それは、疎結合の WSGI ミドルウェアの部品から構成される Web アプリケーション・フレームワークで ある。実際、既存のフレームワーク作者は彼らのフレームワークの既存のサー ビスを、モノリシックなフレームワークというよりこのような WSGI と共に使 用されるライブラリのような方法で提供するためにリファクタリングすること を選ぶかもしれない。そうなれば、アプリケーション開発者は、単一のフレー ムワークのすべての長所と短所に身を委ねる代わりに、特定の機能性のための 「最善の組み合わせの」コンポーネントを選ぶようになるだろう。

Of course, as of this writing, that day is doubtless quite far off. In the meantime, it is a sufficient short-term goal for WSGI to enable the use of any framework with any server.

もちろん、これを書いている現在、そのような日は遥か先のことに違いない。 差し当たりは、あらゆるサーバ、あらゆるフレームワークで WSGI が使用でき るようにすることが短期的目標である。

Finally, it should be mentioned that the current version of WSGI does not prescribe any particular mechanism for “deploying” an application for use with a web server or server gateway. At the present time, this is necessarily implementation-defined by the server or gateway. After a sufficient number of servers and frameworks have implemented WSGI to provide field experience with varying deployment requirements, it may make sense to create another PEP, describing a deployment standard for WSGI servers and application frameworks.

最後に、現在の WSGI ではアプリケーションを Web サーバーまたはサーバゲー トウェイと共に使用するために「配備する」特定のメカニズムは定めないとい うことが言及されるべきである。現在では、これは必ずサーバまたはゲートウェ イの実装毎に定義される。十分な数のサーバとフレームワークが WSGI を実装 し、様々な配備要件を持つ実際の経験が提供されるようになった後で、WSGI サー バとアプリケーションフレームワークの配備仕様について説明する別の PEP を 作成することは価値があるだろう。

Specification Overview

仕様の概要

The WSGI interface has two sides: the “server” or “gateway” side, and the “application” or “framework” side. The server side invokes a callable object that is provided by the application side. The specifics of how that object is provided are up to the server or gateway. It is assumed that some servers or gateways will require an application’s deployer to write a short script to create an instance of the server or gateway, and supply it with the application object. Other servers and gateways may use configuration files or other mechanisms to specify where an application object should be imported from, or otherwise obtained.

WSGI インタフェースには 2 つの側面がある: 「サーバ」または「ゲートウェ イ」サイドと、「アプリケーション」または「フレームワーク」サイド。サー バサイドはアプリケーションサイドによって提供される callable オブジェク トを呼び出す。そのオブジェクトをどのように提供するかに関する詳細はサー バやゲートウェイによって異なる。ある種のサーバまたはゲートウェイは、ア プリケーションの提供者がサーバまたはゲートウェイのインスタンスを作成し、 そのインスタンスにアプリケーションオブジェクトを提供するための短いスク リプトを書くことを要求するだろう。別のサーバまたはゲートウェイは、アプ リケーションオブジェクトがどこからインポートされるべきであるか、または 別の方法で得られるかを指定するために、設定ファイルや他の仕組みを使用す るかもしれない。

In addition to “pure” servers/gateways and applications/frameworks, it is also possible to create “middleware” components that implement both sides of this specification. Such components act as an application to their containing server, and as a server to a contained application, and can be used to provide extended APIs, content transformation, navigation, and other useful functions.

また、「純粋な」サーバ/ゲートウェイとアプリケーション/フレームワークに 加えて、この仕様の両方の側面を実装する「ミドルウェア」コンポーネントを 作成することもできる。そのようなコンポーネントは、サーバに対してはアプ リケーションとして機能すると同時にアプリケーションに対してはサーバとし て機能して、拡張 API 、コンテンツ変換、ナビゲーション、および他の有用な 機能を提供するために使用することができる。

Throughout this specification, we will use the term “a callable” to mean “a function, method, class, or an instance with a __call__ method”. It is up to the server, gateway, or application implementing the callable to choose the appropriate implementation technique for their needs. Conversely, a server, gateway, or application that is invoking a callable must not have any dependency on what kind of callable was provided to it. Callables are only to be called, not introspected upon.

この仕様の全体を通して、 “callable” という用語を、「関数、メソッド、ク ラス、または __call__ メソッドを持つインスタンス」という意味で用い る。callable を実装するサーバ、ゲートウェイ、またはアプリケーションは、 必要に応じて適切な実装のテクニックを選ぶことができる。逆に、 callable を呼び出すサーバ、ゲートウェイ、またはアプリケーションは、どのような callable が提供されるかということに依存してはならない (may not)。 callable は呼び出されるためだけに存在し、その中身を調べるものではない。

The Application/Framework Side

アプリケーション/フレームワークサイド

The application object is simply a callable object that accepts two arguments. The term “object” should not be misconstrued as requiring an actual object instance: a function, method, class, or instance with a __call__ method are all acceptable for use as an application object. Application objects must be able to be invoked more than once, as virtually all servers/gateways (other than CGI) will make such repeated requests.

アプリケーションオブジェクトは、単に2つの引数を受け取る callable オブジェ クトである。「オブジェクト」という用語によって、実際のオブジェクトイン スタンスが必要であると誤解するべきではない: 関数、メソッド、クラス、ま たは __call__ メソッドを持つインスタンスであれば、すべてアプリケー ションオブジェクトとして使用することが許容される。アプリケーションオブ ジェクトは1回以上呼び出すことができなければならない。ほとんどすべての サーバ/ゲートウェイ (CGI を除く) がそのような繰り返された要求をする。

(Note: although we refer to it as an “application” object, this should not be construed to mean that application developers will use WSGI as a web programming API! It is assumed that application developers will continue to use existing, high-level framework services to develop their applications. WSGI is a tool for framework and server developers, and is not intended to directly support application developers.)

(注意: ここでは「アプリケーション」オブジェクトと呼んでいるが、アプリケー ション開発者が WSGI を Web プログラミング API として使用するという意味 でこれを解釈すべきではない! アプリケーション開発者は、彼らのアプリケー ションを開発するのに、既存のハイレベルなフレームワークサービスを利用し 続けると思われる。 WSGI はフレームワークとサーバ開発者のためのツールで あり、直接アプリケーション開発者をサポートすることを意図していない。)

Here are two example application objects; one is a function, and the other is a class:

ここに、2 つのアプリケーションオブジェクトの例がある; 1つは関数であり、 もう片方がクラスである:

def simple_app(environ, start_response):
    """Simplest possible application object"""
    status = '200 OK'
    response_headers = [('Content-type', 'text/plain')]
    start_response(status, response_headers)
    return ['Hello world!\n']


class AppClass:
    """Produce the same output, but using a class

    (Note: 'AppClass' is the "application" here, so calling it
    returns an instance of 'AppClass', which is then the iterable
    return value of the "application callable" as required by
    the spec.

    If we wanted to use *instances* of 'AppClass' as application
    objects instead, we would have to implement a '__call__'
    method, which would be invoked to execute the application,
    and we would need to create an instance for use by the
    server or gateway.
    """

    def __init__(self, environ, start_response):
        self.environ = environ
        self.start = start_response

    def __iter__(self):
        status = '200 OK'
        response_headers = [('Content-type', 'text/plain')]
        self.start(status, response_headers)
        yield "Hello world!\n"

The Server/Gateway Side

サーバー/ゲートウェイサイド

The server or gateway invokes the application callable once for each request it receives from an HTTP client, that is directed at the application. To illustrate, here is a simple CGI gateway, implemented as a function taking an application object. Note that this simple example has limited error handling, because by default an uncaught exception will be dumped to sys.stderr and logged by the web server.

アプリケーションに対して HTTP クライアントから要求があると、サーバやゲー トウェイは、アプリケーション callable を呼び出す。例として、ここではア プリケーションオブジェクトを受け取る関数として実装された簡単な CGI ゲー トウェイを示す。この簡単な例ではエラー処理を省いていることに注意するこ と。デフォルトでは捕捉されなかった例外は sys.stderr に出力され、 Web サーバーのログに記録される。

import os, sys

def run_with_cgi(application):

    environ = dict(os.environ.items())
    environ['wsgi.input']        = sys.stdin
    environ['wsgi.errors']       = sys.stderr
    environ['wsgi.version']      = (1, 0)
    environ['wsgi.multithread']  = False
    environ['wsgi.multiprocess'] = True
    environ['wsgi.run_once']     = True

    if environ.get('HTTPS', 'off') in ('on', '1'):
        environ['wsgi.url_scheme'] = 'https'
    else:
        environ['wsgi.url_scheme'] = 'http'

    headers_set = []
    headers_sent = []

    def write(data):
        if not headers_set:
             raise AssertionError("write() before start_response()")

        elif not headers_sent:
             # Before the first output, send the stored headers
             status, response_headers = headers_sent[:] = headers_set
             sys.stdout.write('Status: %s\r\n' % status)
             for header in response_headers:
                 sys.stdout.write('%s: %s\r\n' % header)
             sys.stdout.write('\r\n')

        sys.stdout.write(data)
        sys.stdout.flush()

    def start_response(status, response_headers, exc_info=None):
        if exc_info:
            try:
                if headers_sent:
                    # Re-raise original exception if headers sent
                    raise exc_info[0], exc_info[1], exc_info[2]
            finally:
                exc_info = None     # avoid dangling circular ref
        elif headers_set:
            raise AssertionError("Headers already set!")

        headers_set[:] = [status, response_headers]
        return write

    result = application(environ, start_response)
    try:
        for data in result:
            if data:    # don't send headers until body appears
                write(data)
        if not headers_sent:
            write('')   # send headers now if body was empty
    finally:
        if hasattr(result, 'close'):
            result.close()

Middleware: Components that Play Both Sides

ミドルウェア: 両サイドを演じるコンポーネント

Note that a single object may play the role of a server with respect to some application(s), while also acting as an application with respect to some server(s). Such “middleware” components can perform such functions as:

単一のオブジェクトが何らかのアプリケーションに関してサーバの役割を果た す一方で、何らかのサーバに対してアプリケーションとして機能するかもしれ ないことに注意すること。そのような「ミドルウェア」コンポーネントは、以 下のような機能を実行することができる:

  • Routing a request to different application objects based on the target URL, after rewriting the environ accordingly.
  • Allowing multiple applications or frameworks to run side-by-side in the same process
  • Load balancing and remote processing, by forwarding requests and responses over a network
  • Perform content postprocessing, such as applying XSL stylesheets
  • 異なるアプリケーションオブジェクトへの要求を、適宜 environ を書き 換えた後で目標 URL に応じてルーティングする
  • 複数のアプリケーションまたはフレームワークが同じプロセス内で並列に稼 働できるようにする
  • リクエストとレスポンスをネットワークの上に転送することによって、負荷 バランスとリモート処理を行う
  • XSL スタイルシートの適用など、コンテンツのポストプロセスを行う
The presence of middleware in general is transparent to both the “server/gateway” and the “application/framework” sides of the interface, and should require no special support. A user who desires to incorporate middleware into an application simply provides the middleware component to the server, as if it were an application, and configures the middleware component to invoke the application, as if the middleware component were a server. Of course, the “application” that the middleware wraps may in fact be another middleware component wrapping another application, and so on, creating what is referred to as a “middleware stack”.

一般に、ミドルウェアの存在はインタフェースの「サーバ/ゲートウェイ」サイ ドと「アプリケーション/フレームワーク」サイドの両方に透過的であり、どん な特別なサポートも必要とするべきではない。ミドルウェアをアプリケーショ ンに組み入れることを望んでいるユーザは、単にミドルウェアコンポーネント を、あたかもそれがアプリケーションであるかのようにサーバに提供する。そ して、ミドルウェアコンポーネントがサーバであるかのように、アプリケーショ ンを呼び出すように設定する。もちろん、ミドルウェアがラップする「アプリ ケーション」は、実際には別のアプリケーションなどをラップする別のミドル ウェアコンポーネントであるかもしれない。それは「ミドルウェアスタック」 と呼ばれるものを作成する。

For the most part, middleware must conform to the restrictions and requirements of both the server and application sides of WSGI. In some cases, however, requirements for middleware are more stringent than for a “pure” server or application, and these points will be noted in the specification.

ほとんどの部分で、ミドルウェアは WSGI のサーバとアプリケーションの両サ イドの制限と要件に従わなければならない。しかしながら、いくつかの場合、 ミドルウェアのための要件は「純粋な」サーバやアプリケーションより厳しい。 これらのポイントは仕様で述べられる。

Here is a (tongue-in-cheek) example of a middleware component that converts text/plain responses to pig latin, using Joe Strout’s piglatin.py. (Note: a “real” middleware component would probably use a more robust way of checking the content type, and should also check for a content encoding. Also, this simple example ignores the possibility that a word might be split across a block boundary.)

これは、 Joe Strout の piglatin.py を使用して、 text/plain レス ポンスから偽ラテン語に変換する、 (tongue-in-cheek; 冗談) ミドルウェアコ ンポーネントの例である。 (注意: 「本物」のミドルウェアコンポーネントは、 おそらく content type をチェックするためにより強健な方法を使用する。ま た、 content encoding もチェックすべきである。また、この簡単な例では、 単語がブロック境界を越えて分割される可能性を無視している。)

from piglatin import piglatin

class LatinIter:

    """Transform iterated output to piglatin, if it's okay to do so

    Note that the "okayness" can change until the application yields
    its first non-empty string, so 'transform_ok' has to be a mutable
    truth value.
    """

    def __init__(self, result, transform_ok):
        if hasattr(result, 'close'):
            self.close = result.close
        self._next = iter(result).next
        self.transform_ok = transform_ok

    def __iter__(self):
        return self

    def next(self):
        if self.transform_ok:
            return piglatin(self._next())
        else:
            return self._next()

class Latinator:

    # by default, don't transform output
    transform = False

    def __init__(self, application):
        self.application = application

    def __call__(self, environ, start_response):

        transform_ok = []

        def start_latin(status, response_headers, exc_info=None):

            # Reset ok flag, in case this is a repeat call
            del transform_ok[:]

            for name, value in response_headers:
                if name.lower() == 'content-type' and value == 'text/plain':
                    transform_ok.append(True)
                    # Strip content-length if present, else it'll be wrong
                    response_headers = [(name, value)
                        for name, value in response_headers
                            if name.lower() != 'content-length'
                    ]
                    break

            write = start_response(status, response_headers, exc_info)

            if transform_ok:
                def write_latin(data):
                    write(piglatin(data))
                return write_latin
            else:
                return write

        return LatinIter(self.application(environ, start_latin), transform_ok)


# Run foo_app under a Latinator's control, using the example CGI gateway
from foo_app import foo_app
run_with_cgi(Latinator(foo_app))

Specification Details

仕様の詳細

The application object must accept two positional arguments. For the sake of illustration, we have named them environ and start_response, but they are not required to have these names. A server or gateway must invoke the application object using positional (not keyword) arguments. (E.g. by calling result = application(environ, start_response) as shown above.)

アプリケーションオブジェクトは2つの固定引数を受け取らなければならない。 説明のためにそれらを environstart_response と名付けるが、こ れらの名前を持つ必要はない。サーバまたはゲートウェイは、 (キーワード引 数ではなく) 固定引数を使用してアプリケーションオブジェクトを呼び出さ な ければならない (must)。 (例えば、上に示されるように、 result = application(environ, start_response) のようにして呼び出す)

The environ parameter is a dictionary object, containing CGI-style environment variables. This object must be a builtin Python dictionary (not a subclass, UserDict or other dictionary emulation), and the application is allowed to modify the dictionary in any way it desires. The dictionary must also include certain WSGI-required variables (described in a later section), and may also include server-specific extension variables, named according to a convention that will be described below.

environ パラメータは、CGI スタイルの環境変数を含む辞書オブジェクト である。このオブジェクトは、 builtin の Python 辞書でなければならない (must) (サブクラス、 UserDict 、または他の辞書エミュレーション では ない)、そしてアプリケーションは好きなように辞書を変更することが できる。辞書は、また、いくつかの必須 WSGI 変数 (後のセクションで説明さ れる) を含まなければならず、また、以下で説明される規約に従って命名され る、サーバ特有の拡張変数を含むことができる。

The start_response parameter is a callable accepting two required positional arguments, and one optional argument. For the sake of illustration, we have named these arguments status, response_headers, and exc_info, but they are not required to have these names, and the application must invoke the start_response callable using positional arguments (e.g. start_response(status, response_headers)).

start_response パラメータは、2つの必須の固定引数、および1つの任意引 数を受け付ける callable である。説明のためにこれらの引数を statusresponse_headers 、および exc_info と命名したが、それらの引数は 必ずしもこのような名前である必要はなく、アプリケーションは固定引数を使 用して start_response callable を呼び出さなければならない (must) (例えば start_response(status, response_headers))。

The status parameter is a status string of the form "999 Message here", and response_headers is a list of (header_name, header_value) tuples describing the HTTP response header. The optional exc_info parameter is described below in the sections on The start_response() Callable and Error Handling. It is used only when the application has trapped an error and is attempting to display an error message to the browser.

status パラメータは "999 Message here" 形式のステータス文字列で あり、 response_headers は HTTP 応答ヘッダーについて記述する (header_name, header_value) タプルのリストである。任意の exc_info パラメータについては、以下の The start_response() Callable セクションと Error Handling セクションで説明される。それ が使用されるのは、アプリケーションがエラーを捕捉し、ブラウザへエラーメッ セージを表示しようとしたときだけである。

The start_response callable must return a write(body_data) callable that takes one positional parameter: a string to be written as part of the HTTP response body. (Note: the write() callable is provided only to support certain existing frameworks’ imperative output APIs; it should not be used by new applications or frameworks if it can be avoided. See the Buffering and Streaming section for more details.)

start_response callable は、 write(body_data) callable を返さな ければならない。 write callable は1つの固定パラメータを取る: HTTP レスポンス本体の一部として書かれるべき文字列。 (注意: write() callable は、いくつかの既存のフレームワークで必須の出力 API をサポート するためだけに提供されている; 避けることができるなら、新しいアプリケー ションまたはフレームワークはそれを使用するべきではない。その他の詳細に 関しては、 Buffering and Streaming セクションを参照。)

When called by the server, the application object must return an iterable yielding zero or more strings. This can be accomplished in a variety of ways, such as by returning a list of strings, or by the application being a generator function that yields strings, or by the application being a class whose instances are iterable. Regardless of how it is accomplished, the application object must always return an iterable yielding zero or more strings.

アプリケーションオブジェクトは、サーバによって呼ばれると、文字列を yield する iterable を返さなければならない。これは、様々な方法で実現す ることができる。例えば、文字列のリストを返すようにする、アプリケーショ ンをジェネレータ関数にしてその関数が文字列を yield するようにする、アプ リケーションをクラスにしてそのインスタンスが iterable であるようにする、 といったような方法である。それがどのように実現されているかにかかわらず、 アプリケーションオブジェクトはいつも文字列を yield する iterable を返さ なければならない。

The server or gateway must transmit the yielded strings to the client in an unbuffered fashion, completing the transmission of each string before requesting another one. (In other words, applications should perform their own buffering. See the Buffering and Streaming section below for more on how application output must be handled.)

サーバまたはゲートウェイは、yield された文字列を非バッファリング形式で クライアントに伝えなければならない。それぞれの文字列の伝達を、別の 1つ を要求する前に終了する。 (言い換えれば、アプリケーションは自身のバッファ リングを実行すべきである (should)。アプリケーション出力をどのように 扱わなければならないかに関して詳しくは、以下の Buffering and Streaming セクションを参照。)

The server or gateway should treat the yielded strings as binary byte sequences: in particular, it should ensure that line endings are not altered. The application is responsible for ensuring that the string(s) to be written are in a format suitable for the client. (The server or gateway may apply HTTP transfer encodings, or perform other transformations for the purpose of implementing HTTP features such as byte-range transmission. See Other HTTP Features, below, for more details.)

サーバまたはゲートウェイは、yield された文字列をバイナリのバイト列とし て扱うべきである: 特に、行末の文字が変更されないことを保証しなければな らない。出力される文字列がクライアントに適当な形式であることを保証する のは、アプリケーションの責任である。 (サーバまたはゲートウェイは、HTTP transfer encoding を適用したり、またはバイト範囲送信などの HTTP 機能を 実行する目的のために他の変更を実行してもよい (may)。その他の詳細に 関して以下の Other HTTP Features を参照。)

If a call to len(iterable) succeeds, the server must be able to rely on the result being accurate. That is, if the iterable returned by the application provides a working __len__() method, it must return an accurate result. (See the Handling the Content-Length Header section for information on how this would normally be used.)

len(iterable) に対する呼び出しが成功する場合、サーバはその結果が正 確であることを信頼できなければならない。すなわち、アプリケーションで返 された iterable が正常に機能する __len__() メソッドを提供するなら、 それは正確な結果を返さなければならない (must)。 (通常これがどのよう に使用されるかに関する情報は、 Handling the Content-Length Header セ クションを参照)

If the iterable returned by the application has a close() method, the server or gateway must call that method upon completion of the current request, whether the request was completed normally, or terminated early due to an error. (This is to support resource release by the application. This protocol is intended to complement PEP 325’s generator support, and other common iterables with close() methods.

もし、アプリケーションで返された iterable が close() メソッドを持っ ているなら、サーバまたはゲートウェイは、現在のリクエストが完了するとき にそのメソッドを呼ばなければならない (must)。これは、リクエストが正 常に処理されたか、またはエラーのために途中で停止されたかに関わらず行わ れる。 (これは、アプリケーションによるリソース解放をサポートするための ものである。このプロトコルは、PEP 325 のジェネレータサポート、および close() メソッドを持つ他の一般的な iterable の補完となることを意図 している)

(Note: the application must invoke the start_response() callable before the iterable yields its first body string, so that the server can send the headers before any body content. However, this invocation may be performed by the iterable’s first iteration, so servers must not assume that start_response() has been called before they begin iterating over the iterable.)

(Note: アプリケーションは、サーバがあらゆる body content の前にヘッダー を送ることができるように、 iterable が最初の body 文字列を yield する前 に start_response() callable を呼び出さなければならない (must)。 しかし、この呼び出しが iterable の最初のイテレーションの際に実行されて もよい (may) ので、サーバは、iterable 上でイテレーションを始める前 に start_response() が呼ばれたと仮定してはならない (must not)。)

Finally, servers and gateways must not directly use any other attributes of the iterable returned by the application, unless it is an instance of a type specific to that server or gateway, such as a “file wrapper” returned by wsgi.file_wrapper (see Optional Platform-Specific File Handling). In the general case, only attributes specified here, or accessed via e.g. the PEP 234 iteration APIs are acceptable.

最後に、サーバとゲートウェイは、アプリケーションから返された iterable の他のいかなる属性も直接使用してはならない (must not)。例外は、 wsgi.file_wrapper によって返された「ファイルラッパー」などのように、 iterable がそのサーバまたはゲートウェイに特定の型のインスタンスである場 合である (Optional Platform-Specific File Handling を参照)。一般的な ケースでは、ここで明記された属性か、または例えば PEP 234 の iteration API を通して属性にアクセスすることだけが許容される。

environ Variables

environ 変数

The environ dictionary is required to contain these CGI environment variables, as defined by the Common Gateway Interface specification [2]. The following variables must be present, unless their value would be an empty string, in which case they may be omitted, except as otherwise noted below.

environ 辞書は、Common Gateway Interface 仕様 [2] で定義されるよう に、これらの CGI 環境変数を含まなければならない。以下の変数は存在しなけ ればならない (must) が、それらの値が空の文字列である場合は、以下に 述べられる例外を除き、省略してもよい (may)。

REQUEST_METHOD

The HTTP request method, such as "GET" or "POST". This cannot ever be an empty string, and so is always required.

"GET" または "POST" などの HTTP リクエストメソッド。これは、 決して空の文字列にならないので、常に必須である。

SCRIPT_NAME

The initial portion of the request URL’s “path” that corresponds to the application object, so that the application knows its virtual “location”. This may be an empty string, if the application corresponds to the “root” of the server.

アプリケーションが仮想的な「位置」を知るための、アプリケーションオブ ジェクトに対応するリクエスト URL の「パス」の最初の部分。アプリケーショ ンがサーバの “root” に一致しているなら、これは空の文字列でもよい (may)。

PATH_INFO

The remainder of the request URL’s “path”, designating the virtual “location” of the request’s target within the application. This may be an empty string, if the request URL targets the application root and does not have a trailing slash.

アプリケーションの中でのリクエストのターゲットの仮想的な「位置」を指 定する、リクエスト URL の「パス」の残りの部分。リクエスト URL がアプ リケーションルートを対象としていて、終端のスラッシュを持っていないな ら。これは空の文字列でもよい (may)。

QUERY_STRING

The portion of the request URL that follows the "?", if any. May be empty or absent.

もしあるならば "?" に続くリクエスト URL の一部。空であるか、また は存在しないかもしれない。

CONTENT_TYPE

The contents of any Content-Type fields in the HTTP request. May be empty or absent.

HTTP リクエスト中の Content-Type フィールドの内容。空であるか、または 存在しないかもしれない。

CONTENT_LENGTH

The contents of any Content-Length fields in the HTTP request. May be empty or absent.

HTTP リクエスト中の Content-Length フィールドの内容。空であるか、 または存在しないかもしれない。

SERVER_NAME, SERVER_PORT

When combined with SCRIPT_NAME and PATH_INFO, these variables can be used to complete the URL. Note, however, that HTTP_HOST, if present, should be used in preference to SERVER_NAME for reconstructing the request URL. See the URL Reconstruction section below for more detail. SERVER_NAME and SERVER_PORT can never be empty strings, and so are always required.

SCRIPT_NAMEPATH_INFO を結合する場合、 URL を完成するのに これらの変数を使用することができる。しかし、もし存在しているなら HTTP_HOST がリクエスト URL を再構築するために SERVER_NAME よ りも優先して使用されるべきであることに注意。その他の詳細に関しては以 下の URL Reconstruction セクションを参照。 SERVER_NAMESERVER_PORT は決して空の文字列にならないので、常に必須である。

SERVER_PROTOCOL

The version of the protocol the client used to send the request. Typically this will be something like "HTTP/1.0" or "HTTP/1.1" and may be used by the application to determine how to treat any HTTP request headers. (This variable should probably be called REQUEST_PROTOCOL, since it denotes the protocol used in the request, and is not necessarily the protocol that will be used in the server’s response. However, for compatibility with CGI we have to keep the existing name.)

クライアントがリクエストを送るのに使用したプロトコルのバージョン。通 常、これは "HTTP/1.0" または "HTTP/1.1" のようになる。そして、 アプリケーションは HTTP リクエストヘッダーも扱う方法を決定するために これらの変数を使用するかもしれない。 (この変数はおそらく REQUEST_PROTOCOL と呼ばれるべきである。なぜなら、それがリクエスト で使用されるプロトコルを指示しており、必ずしもサーバのレスポンスに使 用されるプロトコルというわけではないので。しかしながら、CGI との互換 性のために、我々は既存の名前を維持する必要がある。)

HTTP_ Variables

Variables corresponding to the client-supplied HTTP request headers (i.e., variables whose names begin with "HTTP_"). The presence or absence of these variables should correspond with the presence or absence of the appropriate HTTP header in the request.

クライアントによって提供された HTTP リクエストヘッダ (すなわち、名前 が "HTTP" で始まる変数) これらの変数が存在するかどうかは、リクエ ストにおいて適切な HTTP ヘッダが存在するかどうかに対応するべきである。

A server or gateway should attempt to provide as many other CGI variables as are applicable. In addition, if SSL is in use, the server or gateway should also provide as many of the Apache SSL environment variables [5] as are applicable, such as HTTPS=on and SSL_PROTOCOL. Note, however, that an application that uses any CGI variables other than the ones listed above are necessarily non-portable to web servers that do not support the relevant extensions. (For example, web servers that do not publish files will not be able to provide a meaningful DOCUMENT_ROOT or PATH_TRANSLATED.)

サーバまたはゲートウェイは、他の CGI 変数に関しても適切なものはできるだ け多く提供しようと努力すべきである (should)。加えて、SSL が使用中な ら、サーバまたはゲートウェイは Apache SSL 環境変数 [5] のうち適切なも のはできるだけ多く提供すべきである (should)。例えば HTTPS=onSSL_PROTOCOL など。しかし、上に記載された以外の CGI 変数を使用する アプリケーションは、関連する拡張をサポートしない Web サーバーに必ずしも 移植可能でないことに注意。 (例えば、ファイルを出力しない Web サーバーは、 意味のある DOCUMENT_ROOTPATH_TRANSLATED を提供することがで きないだろう。)

A WSGI-compliant server or gateway should document what variables it provides, along with their definitions as appropriate. Applications should check for the presence of any variables they require, and have a fallback plan in the event such a variable is absent.

WSGI 対応のサーバまたはゲートウェイは、どんな変数を提供するかをその定義 と共に適切に文書化すべきである (should)。アプリケーションは、必要と する変数が存在するかどうかをチェックして、そのような変数が存在しない場 合の fallback プランを持つべきである (should)。

Note: missing variables (such as REMOTE_USER when no authentication has occurred) should be left out of the environ dictionary. Also note that CGI-defined variables must be strings, if they are present at all. It is a violation of this specification for a CGI variable’s value to be of any type other than str.

注意: 欠けている変数 (認証が行われていない場合の REMOTE_USER など) は、 environ 辞書からは除かれるべきである。また、CGI 定義変数は、も し存在するなら文字列でなければならないことに注意。 CGI 変数の値が str 以外のどんな型であっても、この仕様に対する違反である。

In addition to the CGI-defined variables, the environ dictionary may also contain arbitrary operating-system “environment variables”, and must contain the following WSGI-defined variables:

CGI 定義変数に加えて、 environ 辞書は、任意の OS「環境変数」を含ん でもよい (may)。そして、以下の WSGI 定義変数を含まなければならない (must):

wsgi.version

The tuple (1, 0), representing WSGI version 1.0.

WSGI version 1.0 を表す、タプル (1, 0)

wsgi.url_scheme

A string representing the “scheme” portion of the URL at which the application is being invoked. Normally, this will have the value "http" or "https", as appropriate.

アプリケーションが呼び出された URL の「スキーム」 部分を表す文字列。通常これは "http" または "https" のどちらか適切な値を持つ。

wsgi.input

An input stream (file-like object) from which the HTTP request body can be read. (The server or gateway may perform reads on-demand as requested by the application, or it may pre- read the client’s request body and buffer it in-memory or on disk, or use any other technique for providing such an input stream, according to its preference.)

HTTP リクエスト本体を読み出すことができる入力ス トリーム (file-like オブジェクト)。 (サーバまた はゲートウェイは、アプリケーションからの要求に応 じて読み出しを実行するか、またはクライアントのリ クエスト本体を事前に読み出して、メモリまたはディ スクの上にそれをバッファリングするか、あるいはそ のような入力ストリームを提供するための他のいかな るテクニックも、好みに従って使用してもよい。)

wsgi.errors

An output stream (file-like object) to which error output can be written, for the purpose of recording program or other errors in a standardized and possibly centralized location. This should be a “text mode” stream; i.e., applications should use "\n" as a line ending, and assume that it will be converted to the correct line ending by the server/gateway.

エラー出力を書き込むことができる出力ストリーム (file-like オブジェクト)。プログラムや他のエラー を、標準化された、場合によっては集約された場所に 記録する目的のために用いられる。これは「テキスト モード」ストリームであるべきである; すなわち、ア プリケーションは行末端として "\n" を使用して、 それがサーバ/ゲートウェイによって正しい行末端に 変換されると仮定すべきである。

For many servers, wsgi.errors will be the server’s main error log. Alternatively, this may be sys.stderr, or a log file of some sort. The server’s documentation should include an explanation of how to configure this or where to find the recorded output. A server or gateway may supply different error streams to different applications, if this is desired.

多くのサーバでは、 wsgi.errors はサーバ本体 のエラーログになるだろう。代わりに、これは sys.stderr またはある種のログファイルでもよ い。サーバのドキュメンテーションはどのようにこれ を設定するか、または記録された出力をどこで見つけ られるかに関する説明を含むべきである。サーバまた はゲートウェイは、もし望まれているなら、異なった アプリケーションに対して異なったエラーストリーム を提供してもよい。

wsgi.multithread

This value should evaluate true if the application object may be simultaneously invoked by another thread in the same process, and should evaluate false otherwise.

アプリケーションオブジェクトが同じプロセスの中で 同時に別のスレッドによって呼び出されることがある なら、この値は true と評価されるべきであり、そう でなければこの値は false と評価されるべきである。

wsgi.multiprocess

This value should evaluate true if an equivalent application object may be simultaneously invoked by another process, and should evaluate false otherwise.

等価なアプリケーションオブジェクトが、同時に別の プロセスによって呼び出されることがあるなら、この 値は true と評価されるべきであり、そうでなければ false と評価されるべきである。

wsgi.run_once

This value should evaluate true if the server or gateway expects (but does not guarantee!) that the application will only be invoked this one time during the life of its containing process. Normally, this will only be true for a gateway based on CGI (or something similar).

この値は、サーバまたはゲートウェイが、プロセスの 寿命の間にアプリケーションが呼び出されるのはこの 1回だけであると期待する (しかし、保証はしない!) 場合に、true と評価されるべきである。通常、これ は CGI (または同様の何か) に基づくゲートウェイだ けで true になるだろう。

Finally, the environ dictionary may also contain server-defined variables. These variables should be named using only lower-case letters, numbers, dots, and underscores, and should be prefixed with a name that is unique to the defining server or gateway. For example, mod_python might define variables with names like mod_python.some_variable.

最後に、 environ 辞書はサーバ定義変数を含んでもよい。これらの変数は、 アルファベット小文字、数字、ドット、およびアンダースコアだけを使用して 命名されるべきである。そしてそれを定義するサーバまたはゲートウェイにユ ニークな名前をプリフィックスとして付加すべきである。例えば、 mod_pythonmod_python.some_valiable のような名前で変数を定義 するだろう。

Input and Error Streams

入力およびエラーストリーム

The input and error streams provided by the server must support the following methods:

サーバによって提供された入力およびエラーストリームは、以下のメソッドを サポートしなければならない:

Method Stream Notes
read(size) input 1
readline() input 1, 2
readlines(hint) input 1, 3
__iter__() input  
flush() errors 4
write(str) errors  
writelines(seq) errors  
The semantics of each method are as documented in the Python Library Reference, except for these notes as listed in the table above:

それぞれのメソッドの意味は、上の表にリストアップされている注記を例外と して、Python Library Reference の中で以下のように文書化されている:

  1. The server is not required to read past the client’s specified Content-Length, and is allowed to simulate an end-of-file condition if the application attempts to read past that point. The application should not attempt to read more data than is specified by the CONTENT_LENGTH variable.
  1. サーバは、クライアントの指定した Content-Length を越えて読み出す 必要はなく、アプリケーションがそのポイントを越えて読み出そうとした場 合に、end-of-file 状態をシミュレートすることが許される。アプリケーショ ンは、 CONTENT_LENGTH 変数によって指定されるより多くのデータを読 み出そうとすべきでない (should not)。
  1. The optional “size” argument to readline() is not supported, as it may be complex for server authors to implement, and is not often used in practice.
  1. readline() への任意の「サイズ」引数はサポートされない。なぜなら、 それはサーバ作者が実装するには複雑で、しかも実際にはしばしば使用され ないためだ。
  1. Note that the hint argument to readlines() is optional for both caller and implementer. The application is free not to supply it, and the server or gateway is free to ignore it.
  1. readlines() への hint 引数は、それを呼ぶ側と実装する側の両方 に対して任意であることに注意。アプリケーションがそれを提供しないのは 自由であり、そしてサーバまたはゲートウェイは自由にそれを無視すること ができる。
  1. Since the errors stream may not be rewound, servers and gateways are free to forward write operations immediately, without buffering. In this case, the flush() method may be a no-op. Portable applications, however, cannot assume that output is unbuffered or that flush() is a no-op. They must call flush() if they need to ensure that output has in fact been written. (For example, to minimize intermingling of data from multiple processes writing to the same error log.)
  1. errors ストリームは巻き戻されないので、サーバやゲートウェイは書 き込み操作をバッファリングなしで即座に進めることができる。この場合、 flush() メソッドは何もしない (no-op) かもしれない。しかし、移植 性のあるアプリケーションでは、出力がバッファリングされないことや、 flush() が no-op であることを仮定することはできない。出力が実際 に書かれていることを保証する必要があるなら flush() を呼ばなけれ ばならない。 (例えば、同じエラーログに書いている複数のプロセスから、 データの混り合いを最小にするために。)
The methods listed in the table above must be supported by all servers conforming to this specification. Applications conforming to this specification must not use any other methods or attributes of the input or errors objects. In particular, applications must not attempt to close these streams, even if they possess close() methods.

上の表に記載されたメソッドは、この仕様に従うすべてのサーバでサポートさ れなければならない (must)。この仕様に従うアプリケーションは、 input または errors オブジェクトのいかなる他のメソッドまたは属 性も使用してはならない (must not)。特に、それらが close() メソッ ドを持っていても、アプリケーションはこれらのストリームを閉じようとして はならない (must not)。

The start_response() Callable

The second parameter passed to the application object is a callable of the form start_response(status, response_headers, exc_info=None). (As with all WSGI callables, the arguments must be supplied positionally, not by keyword.) The start_response callable is used to begin the HTTP response, and it must return a write(body_data) callable (see the Buffering and Streaming section, below).

アプリケーションオブジェクトに渡された 2番目のパラメータは、 start_response(status, response_headers, exc_info=None) 形式の callable である (すべての WSGI callables と同様、引数はキーワード引数で はなく固定引数で提供されなければならない)。 start_response callable は、HTTP レスポンスを開始するために使用される。そして、それは write(body_data) callable を返さなければならない。 (以下の Buffering and Streaming セクションを参照)。

The status argument is an HTTP “status” string like "200 OK" or "404 Not Found". That is, it is a string consisting of a Status-Code and a Reason-Phrase, in that order and separated by a single space, with no surrounding whitespace or other characters. (See RFC 2616, Section 6.1.1 for more information.) The string must not contain control characters, and must not be terminated with a carriage return, linefeed, or combination thereof.

status 引数は、 "200 OK""404 Not Found" のような、HTTP 「ステータス」文字列である。すなわち、それは Status-Code と Reason-Phrase をこの順番で含む文字列で、シングルスペースによって分離さ れ、全体を囲む空白または他の文字列を持たない (詳しい情報に関しては RFC 2616 セクション 6.1.1 を参照)。その文字列は、制御文字を含んではならない (must not)。また、復帰、ラインフィード、またはそれらの組み合わせで 終わってはならない。

The response_headers argument is a list of (header_name, header_value) tuples. It must be a Python list; i.e. type(response_headers) is ListType, and the server may change its contents in any way it desires. Each header_name must be a valid HTTP header field-name (as defined by RFC 2616, Section 4.2), without a trailing colon or other punctuation.

response_headers 引数は、 (header_name, header_value) タプルの リストである。それは Python リストでなければならない; すなわち、 type(response_headers) is ListType である。そして、サーバはその内容 を自由に変更してもよい (may)。それぞれの header_name は有効な HTTP ヘッダフィールド名 (RFC 2616 セクション 4.2 によって定義されるよう に) でなければならず、末尾のコロンも他の記号も含まない。

Each header_value must not include any control characters, including carriage returns or linefeeds, either embedded or at the end. (These requirements are to minimize the complexity of any parsing that must be performed by servers, gateways, and intermediate response processors that need to inspect or modify response headers.)

それぞれの header_value は、復帰またはラインフィードを含む どんな 制御文字も、埋め込まれているか末尾かどうかに関わらず、含んではならない (must not)。 (これらの要件は、サーバ、ゲートウェイ、およびレスポン スヘッダーを inspect または変更する必要のある中間的レスポンス・プロセッ サで実行しなければならない構文解析の複雑さを最小にするためである。)

In general, the server or gateway is responsible for ensuring that correct headers are sent to the client: if the application omits a header required by HTTP (or other relevant specifications that are in effect), the server or gateway must add it. For example, the HTTP Date: and Server: headers would normally be supplied by the server or gateway.

一般に、サーバまたはゲートウェイは、正しいヘッダーが確実にクライアント に送られることに対する責任を負う: もしアプリケーションが HTTP (あるいは 効力を持った関連する他の仕様) によって必要とされるヘッダーを省略するな ら、サーバまたはゲートウェイがそれを加えなければならない (must)。例 えば、HTTP Date:Server: ヘッダーは、通常、サーバまたはゲー トウェイによって提供されるだろう。

(A reminder for server/gateway authors: HTTP header names are case-insensitive, so be sure to take that into consideration when examining application-supplied headers!)

(サーバ/ゲートウェイ作者のためのリマインダー: HTTP ヘッダ名は文字の大小 を区別しないので、アプリケーションで提供されたヘッダーを調べるとき、そ れを必ず考慮に入れること!)

Applications and middleware are forbidden from using HTTP/1.1 “hop-by-hop” features or headers, any equivalent features in HTTP/1.0, or any headers that would affect the persistence of the client’s connection to the web server. These features are the exclusive province of the actual web server, and a server or gateway should consider it a fatal error for an application to attempt sending them, and raise an error if they are supplied to start_response(). (For more specifics on “hop-by-hop” features and headers, please see the Other HTTP Features section below.)

アプリケーションとミドルウェアは、HTTP/1.1 の”hop-by-hop”機能またはヘッ ダーや、HTTP/1.0 における同等の機能や、あるいはクライアントから Web サー バーへの接続の永続性に影響するどんなヘッダーも、使用することは禁止され る。これらの機能は、本物の Web サーバーに排他的な領域である。サーバある いはゲートウェイは、アプリケーションがそれらを送ろうとすることは致命的 なエラーであるとみなし、それらが start_response() に提供された場合、 エラーを raise すべきである (should)。 (「hop-by-hop」の機能とヘッ ダーに関してより多くの詳細は、以下の Other HTTP Features セクション を参照。)

The start_response callable must not actually transmit the response headers. Instead, it must store them for the server or gateway to transmit only after the first iteration of the application return value that yields a non-empty string, or upon the application’s first invocation of the write() callable. In other words, response headers must not be sent until there is actual body data available, or until the application’s returned iterable is exhausted. (The only possible exception to this rule is if the response headers explicitly include a Content-Length of zero.)

start_response callable は、実際にレスポンスヘッダーを送信してはな らない (must not)。代わりに、空でない文字列を yield するアプリケー ション戻り値の最初の繰り返しの後か、アプリケーションの write() callable の最初の呼び出しの時に だけ 送信するように、レスポンスヘッ ダをサーバまたはゲートウェイに格納しなければならない。言い換えれば、実 際のボディーデータが利用可能になるか、またはアプリケーションの返された iterable が消費されるまで、レスポンスヘッダーを送ってはならない。 (この 規則に対する可能な唯一の例外は、レスポンスヘッダーが明示的に 0 の Content-Length を含む場合である。)

This delaying of response header transmission is to ensure that buffered and asynchronous applications can replace their originally intended output with error output, up until the last possible moment. For example, the application may need to change the response status from “200 OK” to “500 Internal Error”, if an error occurs while the body is being generated within an application buffer.

レスポンスヘッダー送信のこの遅延は、バッファリングされる非同期なアプリ ケーションが、元々意図された出力をエラー出力に取り替えることが最後の可 能な瞬間までできることを保証するためである。例えば、アプリケーションバッ ファの中でボディーが生成されている間にエラーが発生するなら、アプリケー ションは、レスポンスステータスを「200 OK」から「500 Internal Error」に 変える必要があるかもしれない。

The exc_info argument, if supplied, must be a Python sys.exc_info() tuple. This argument should be supplied by the application only if start_response is being called by an error handler. If exc_info is supplied, and no HTTP headers have been output yet, start_response should replace the currently-stored HTTP response headers with the newly-supplied ones, thus allowing the application to “change its mind” about the output when an error has occurred.

exc_info 引数は、もし提供されるなら Python の sys.exc_info() タ プルでなければならない。アプリケーションは、エラーハンドラが start_response を呼んでいる場合にだけ、この引数を提供するべきである。 もし exc_info が提供されていて、まだ何も HTTP ヘッダが出力されてい ないなら、 start_response は、現在格納された HTTP レスポンスヘッダー を新たに提供されたものに置き換えるべきである。その結果、エラーが発生し たときにアプリケーションが出力に関して「気が変わる」ことを許容する。

However, if exc_info is provided, and the HTTP headers have already been sent, start_response must raise an error, and should raise the exc_info tuple. That is:

しかし、 exc_info が提供されていて、 HTTP ヘッダが既に送られた後なら、 start_response はエラーを raise しなければならず (must)、 exc_info タプルを raise すべきである (should)。以下のように:

raise exc_info[0], exc_info[1], exc_info[2]
This will re-raise the exception trapped by the application, and in principle should abort the application. (It is not safe for the application to attempt error output to the browser once the HTTP headers have already been sent.) The application must not trap any exceptions raised by start_response, if it called start_response with exc_info. Instead, it should allow such exceptions to propagate back to the server or gateway. See Error Handling below, for more details.

これは、アプリケーションで捕捉された例外を再び送出する。そして原則とし てアプリケーションを中止させるべきである。 (いったん HTTP ヘッダが送ら れると、アプリケーションがブラウザにエラー出力を試みることは安全ではな い。) アプリケーションは、 exc_info を用いて start_response を 呼んだ場合、 start_response で発生したどんな例外も捕捉してはならな い (must not)。代わりに、そのような例外がサーバまたはゲートウェイに 逆伝播することを許すべきである。その他の詳細に関して、以下の Error Handling を参照。

The application may call start_response more than once, if and only if the exc_info argument is provided. More precisely, it is a fatal error to call start_response without the exc_info argument if start_response has already been called within the current invocation of the application. (See the example CGI gateway above for an illustration of the correct logic.)

アプリケーションは、 exc_info 引数が提供される場合にだけ、 start_response を複数回呼んでもよい (may)。より正確には、アプリ ケーションの現在の呼び出しの中で既に start_response が呼ばれたなら、 exc_info 引数なしで start_response を呼ぶのは致命的なエラーであ る。 (正しい論理の例証のために、上の CGI ゲートウェイの例を参照。)

Note: servers, gateways, or middleware implementing start_response should ensure that no reference is held to the exc_info parameter beyond the duration of the function’s execution, to avoid creating a circular reference through the traceback and frames involved. The simplest way to do this is something like:

注意: start_response を実装するサーバ、ゲートウェイ、またはミドルウェ アは、関係するトレースバックとフレームを通して循環参照を作成するのを避 けるために、関数の実行の持続時間を超えて exc_info パラメータへの参 照を保持しないことを確実にすべきである (should)。これを行う最も簡単 な方法は以下のようになる:

def start_response(status, response_headers, exc_info=None):
    if exc_info:
         try:
             # do stuff w/exc_info here
         finally:
             exc_info = None    # Avoid circular ref.
The example CGI gateway provides another illustration of this technique.

例の CGI ゲートウェイはこのテクニックの別の例を提供する。

Handling the Content-Length Header

Content-Length ヘッダーの扱い

If the application does not supply a Content-Length header, a server or gateway may choose one of several approaches to handling it. The simplest of these is to close the client connection when the response is completed.

アプリケーションが Content-Length ヘッダーを提供しないなら、サーバ またはゲートウェイは、それを扱うためにいくつかのアプローチの 1つを選ん でもよい。最も簡単なのは、レスポンスが終了したときにクライアント接続を 閉じることである。

Under some circumstances, however, the server or gateway may be able to either generate a Content-Length header, or at least avoid the need to close the client connection. If the application does not call the write() callable, and returns an iterable whose len() is 1, then the server can automatically determine Content-Length by taking the length of the first string yielded by the iterable.

しかしながら、いくつかの状況では、サーバまたはゲートウェイが Content-Length ヘッダーを生成するか、または少なくともクライアント接 続を閉じる必要性を避けることができるかもしれない。アプリケーションが write() callable を呼び出して いなくて 、 iterable を返し、その len() が 1 である場合、サーバは、 iterable によって yield された最 初の文字列の長さを取得しながら自動的に Content-Length を決定するこ とができる。

And, if the server and client both support HTTP/1.1 “chunked encoding” [3], then the server may use chunked encoding to send a chunk for each write() call or string yielded by the iterable, thus generating a Content-Length header for each chunk. This allows the server to keep the client connection alive, if it wishes to do so. Note that the server must comply fully with RFC 2616 when doing this, or else fall back to one of the other strategies for dealing with the absence of Content-Length.

そして、サーバとクライアントがともに HTTP/1.1 “chunked encoding” [3] をサポー トするなら、サーバは各 write() の呼び出しまたは iterable によって yield された文字列のチャンクを送るのに chunked encoding を使用してもよ い (may)。すなわち、チャンク毎に Content-Length ヘッダーを生成 する。これによって、サーバはもしそれを望むならクライアント接続を持続で きる。これをするとき、サーバが RFC 2616 に完全に従わなければならない (must) ことに注意。そうでなければ、 Content-Length が存在しない ことに対処するための他の戦略の 1 つに fall back すること。

(Note: applications and middleware must not apply any kind of Transfer-Encoding to their output, such as chunking or gzipping; as “hop-by-hop” operations, these encodings are the province of the actual web server/gateway. See Other HTTP Features below, for more details.)

(注意: アプリケーションおよびミドルウェアは、出力に chunking や gzipping などのどんな種類の Transfer-Encoding も適用してはならない (must not); “hop-by-hop” 操作と同様に、これらのエンコーディングは本 物の Web サーバー/ゲートウェイの領域である。その他の詳細に関しては、以 下の Other HTTP Features を参照。)

Buffering and Streaming

バッファリングとストリーミング

Generally speaking, applications will achieve the best throughput by buffering their (modestly-sized) output and sending it all at once. This is a common approach in existing frameworks such as Zope: the output is buffered in a StringIO or similar object, then transmitted all at once, along with the response headers.

一般的に、アプリケーションは、自身の (適切なサイズの) 出力をバッファリ ングして、それを一気に送ることによって、最も良い効率を実現するだろう。 これは Zope などの既存のフレームワークで一般的なアプローチである: 出力 は StringIO または同様の物でバッファリングされ、次にレスポンスヘッダー と共に一気に送信される。

The corresponding approach in WSGI is for the application to simply return a single-element iterable (such as a list) containing the response body as a single string. This is the recommended approach for the vast majority of application functions, that render HTML pages whose text easily fits in memory.

WSGI における対応するアプローチは、アプリケーションが単に、単一の文字列 としてレスポンス本体を含む、ただ 1つの要素の iterable (リストなど) を返 すことである。これは、そのテキストが容易にメモリに収まる HTML ページを 描画するような、アプリケーション機能のほとんどの部分におけるお勧めのア プローチである。

For large files, however, or for specialized uses of HTTP streaming (such as multipart “server push”), an application may need to provide output in smaller blocks (e.g. to avoid loading a large file into memory). It’s also sometimes the case that part of a response may be time-consuming to produce, but it would be useful to send ahead the portion of the response that precedes it.

しかしながら、大きいファイル、または HTTP ストリーミングの特殊な用途 (複合「サーバプッシュ」など) のために、アプリケーションは出力をより小さ なブロックに提供する必要があるかもしれない (例えばメモリに大きいファイ ルをロードすることを避けるため)。また、応答のある部分を生成するのに時間 がかかる場合も時々あるが、それに先行するレスポンスの部分を前もって送る ことは役に立つだろう。

In these cases, applications will usually return an iterator (often a generator-iterator) that produces the output in a block-by-block fashion. These blocks may be broken to coincide with mulitpart boundaries (for “server push”), or just before time-consuming tasks (such as reading another block of an on-disk file).

これらの場合では、通常、アプリケーションはブロックごとの様式で出力を生 成するイテレータ (しばしばジェネレータ・イテレータ) を返すだろう。これ らのブロックは、 mulitpart 境界 (「サーバプッシュ」のための) や、時間の かかるタスク (ディスクに存在するファイルの別のブロックを読むなど) のす ぐ前で分割が起こるかもしれない。

WSGI servers, gateways, and middleware must not delay the transmission of any block; they must either fully transmit the block to the client, or guarantee that they will continue transmission even while the application is producing its next block. A server/gateway or middleware may provide this guarantee in one of three ways:

WSGI サーバ、ゲートウェイ、およびミドルウェアは、どんなブロックの送信も 遅延してはならない (must not); ブロックをクライアントに完全に伝える か、またはアプリケーションが次のブロックを作り出している間も送信を続け ることを保証しなければならない (must)。サーバ/ゲートウェイまたはミ ドルウェアは、次の 3つの方法のうちの 1つで、この保証を提供することがで きる:

  1. Send the entire block to the operating system (and request that any O/S buffers be flushed) before returning control to the application, OR
  1. 制御をアプリケーションに返す前に、ブロック全体を OS に送る (そして、 あらゆる OS バッファが flush されることを要求する)。
  1. Use a different thread to ensure that the block continues to be transmitted while the application produces the next block.
  1. 別のスレッドを使用して、アプリケーションが次のブロックを作り出してい る間もブロックの送信が続けられることを保証する。
  1. (Middleware only) send the entire block to its parent gateway/server
  1. (ミドルウェアのみ) ブロック全体を、親のゲートウェイまたはサーバに送る
By providing this guarantee, WSGI allows applications to ensure that transmission will not become stalled at an arbitrary point in their output data. This is critical for proper functioning of e.g. multipart “server push” streaming, where data between multipart boundaries should be transmitted in full to the client.

この保証を提供することによって、WSGI は送信が出力データの任意のポイント で中断しないことをアプリケーションが保証することを可能にする。適切な機 能にとって、これは重要である。例えば、複合「サーバプッシュ」ストリーミ ングでは、複合境界の間のデータはクライアントにすべて送られなければなら ない。

Middleware Handling of Block Boundaries

ブロック境界を扱うミドルウェア

In order to better support asynchronous applications and servers, middleware components must not block iteration waiting for multiple values from an application iterable. If the middleware needs to accumulate more data from the application before it can produce any output, it must yield an empty string.

非同期のアプリケーションおよびサーバのより良いサポートのために、ミドル ウェアコンポーネントはアプリケーション iterable から複数の値を待ってい る間、イテレーションをブロックしてはならない (must not)。ミドルウェ アが出力を生成できるようになる前に、アプリケーションからより多くのデー タを蓄積する必要があるなら、空の文字列を yield しなければならない (must)。

To put this requirement another way, a middleware component must yield at least one value each time its underlying application yields a value. If the middleware cannot yield any other value, it must yield an empty string.

この要件を言い換えれば、ミドルウェアコンポーネントは内包するアプリケー ションが値を yield する毎に 少なくとも 1つの値を yield しなければなら ない 。ミドルウェアが他の値を yield することができないなら、空の文字 列をyield しなければならない。

This requirement ensures that asynchronous applications and servers can conspire to reduce the number of threads that are required to run a given number of application instances simultaneously.

この要件は、非同期なアプリケーションとサーバが協力して、与えられた数の アプリケーションインスタンスを同時に実行するのに必要なスレッドの数を減 らすことができることを保証する。

Note also that this requirement means that middleware must return an iterable as soon as its underlying application returns an iterable. It is also forbidden for middleware to use the write() callable to transmit data that is yielded by an underlying application. Middleware may only use their parent server’s write() callable to transmit data that the underlying application sent using a middleware-provided write() callable.

また、この要件が、ミドルウェアは内包するアプリケーションが iterable を 返すとすぐに iterable を返さなければならない (must) ということを意 味することに注意。また、ミドルウェアは、内包するアプリケーションから yield されたデータを送信するために write() callable を使用すること が禁止される。ミドルウェアは、内包するアプリケーションがミドルウェアか ら提供された``write()`` callable を使用して送ったデータを送信するために だけ、親サーバの write() callable を使用することができる。

The write() Callable

Some existing application framework APIs support unbuffered output in a different manner than WSGI. Specifically, they provide a “write” function or method of some kind to write an unbuffered block of data, or else they provide a buffered “write” function and a “flush” mechanism to flush the buffer.

いくつかの既存のアプリケーション・フレームワーク API は、WSGI と異なっ た方法で非バッファリング出力をサポートする。特に、 “write” 関数またはあ る種のバッファリングされないデータのブロックを書くための方法を提供した り、または、バッファリングされる “write” 関数と、バッファをフラッシュす るための “flush” メカニズムを提供したりする。

Unfortunately, such APIs cannot be implemented in terms of WSGI’s “iterable” application return value, unless threads or other special mechanisms are used.

残念ながら、そのような API はスレッドや他の特別なメカニズムが使用されて いない限り、WSGI の “iterable” アプリケーション戻り値の方法では実装する ことができない。

Therefore, to allow these frameworks to continue using an imperative API, WSGI includes a special write() callable, returned by the start_response callable.

したがって、これらのフレームワークが必須の API を使用し続けることを許容 するために、 WSGI は特別な write() callable を含んでいる。それは、 start_response callable によって返される。

New WSGI applications and frameworks should not use the write() callable if it is possible to avoid doing so. The write() callable is strictly a hack to support imperative streaming APIs. In general, applications should produce their output via their returned iterable, as this makes it possible for web servers to interleave other tasks in the same Python thread, potentially providing better throughput for the server as a whole.

新しい WSGI アプリケーションとフレームワークは、可能なら write() callable を使用すべきでない (should not)。 write() callable は、 不可避のストリーミング API をサポートするための完全なハックである。一般 に、アプリケーションはその戻り値の iterable によって出力を生成すべきで ある。これによって Web サーバーは、同じ Python スレッドにおける他のタス クを相互に切り替えることが可能になり、潜在的にサーバ全体でより良い効率 を提供することができる。

The write() callable is returned by the start_response() callable, and it accepts a single parameter: a string to be written as part of the HTTP response body, that is treated exactly as though it had been yielded by the output iterable. In other words, before write() returns, it must guarantee that the passed-in string was either completely sent to the client, or that it is buffered for transmission while the application proceeds onward.

write() callable は start_response() callable によって返される。 そして、ただ一つのパラメータを受け付ける: HTTP レスポンスボディの一部と して書き出されるべき文字列。それは、出力 iterable によって yield された 場合と同じように扱われる。言い換えれば、 write() が戻る前に、渡され た文字列をクライアントに完全に送信するか、あるいはアプリケーションが先 に進んでいる間、送信のためにそれをバッファリングすることを保証しなけれ ばならない。

An application must return an iterable object, even if it uses write() to produce all or part of its response body. The returned iterable may be empty (i.e. yield no non-empty strings), but if it does yield non-empty strings, that output must be treated normally by the server or gateway (i.e., it must be sent or queued immediately). Applications must not invoke write() from within their return iterable, and therefore any strings yielded by the iterable are transmitted after all strings passed to write() have been sent to the client.

アプリケーションはレスポンスボディのすべてまたは一部を生成するのに write() を使用した場合でも、 iterable オブジェクトを返さなければな らない (must)。返された iterable は空でもよい (may) (すなわち、 空でない文字列を一切 yield しない) が、空でない文字列を yield する な ら、サーバまたはゲートウェイはその出力を通常と同じように扱わなければな らない (すなわち、それをすぐに送信するか、またはキューに入れる)。アプリ ケーションは、自身の返した iterable から write() を呼び出してはなら ない (must not)。そして、したがって、iterable によって yield された どんな文字列も、 write() に渡されたすべての文字列をクライアントに送っ た後で送信される。

Unicode Issues

Unicode の問題

HTTP does not directly support Unicode, and neither does this interface. All encoding/decoding must be handled by the application; all strings passed to or from the server must be standard Python byte strings, not Unicode objects. The result of using a Unicode object where a string object is required, is undefined.

HTTP は Unicode を直接サポートしない。そして、このインタフェースも同様 である。すべてのエンコード/デコードは、アプリケーションで扱われなければ ならない; サーバに渡された、またはサーバから渡されたすべての文字列は、 Unicode オブジェクトではなく、 Python の標準バイト文字列でなければなら ない。文字列オブジェクトが必要な局面で Unicode オブジェクトを使用した結 果は、未定義である。

Note also that strings passed to start_response() as a status or as response headers must follow RFC 2616 with respect to encoding. That is, they must either be ISO-8859-1 characters, or use RFC 2047 MIME encoding.

また、 start_response() にステータスまたはレスポンスヘッダーとして 渡された文字列は、コード化に関して RFC 2616 に従わなければならない (must) ことに注意。すなわち、それらは、ISO-8859-1 文字列であるか、 または RFC 2047 のMIME エンコーディングを使用しなければならない。

On Python platforms where the str or StringType type is in fact Unicode-based (e.g. Jython, IronPython, Python 3000, etc.), all “strings” referred to in this specification must contain only code points representable in ISO-8859-1 encoding (\u0000 through \u00FF, inclusive). It is a fatal error for an application to supply strings containing any other Unicode character or code point. Similarly, servers and gateways must not supply strings to an application containing any other Unicode characters.

str 型や StringType 型が実際には Unicode ベースである Python プ ラットホーム (例えば Jython, IronPython, Python 3000 など) であっても、 この仕様で言及されたすべての「文字列」は、 ISO-8859-1 エンコーディング で表現可能なコード・ポイント (\u0000 から \u00FF まで) だけで構 成されなければならない。アプリケーションがこの範囲外の Unicode 文字また はコード・ポイントを含む文字列を渡すのは、致命的なエラーである。同様に、 サーバおよびゲートウェイは、この範囲外の Unicode 文字を含む文字列をアプ リケーションに渡してはならない (must not)。

Again, all strings referred to in this specification must be of type str or StringType, and must not be of type unicode or UnicodeType. And, even if a given platform allows for more than 8 bits per character in str/StringType objects, only the lower 8 bits may be used, for any value referred to in this specification as a “string”.

繰り返すが、この仕様で言及されたすべての文字列は、 str 型または StringType 型でなければならず (must)、 unicode 型または UnicodeType 型であってはならない (must not)。そして、プラットホー ムが str/StringType オブジェクトに 1文字あたり 8ビット以上を許 可している場合でも、この仕様で「文字列」と呼ばれた値に対しては、下位の 8 ビットだけしか使用することができない。

Error Handling

エラー処理

In general, applications should try to trap their own, internal errors, and display a helpful message in the browser. (It is up to the application to decide what “helpful” means in this context.)

一般に、アプリケーションはそれ自身の内部エラーを捕捉し、ブラウザに有用 なメッセージを表示すべきである (should)。 (この文脈において、「有用」 が何を意味するのかを決めるのは、アプリケーション次第である)

However, to display such a message, the application must not have actually sent any data to the browser yet, or else it risks corrupting the response. WSGI therefore provides a mechanism to either allow the application to send its error message, or be automatically aborted: the exc_info argument to start_response. Here is an example of its use:

しかしながら、そのようなメッセージを表示するためには、アプリケーション は実際にはどんなデータもまだブラウザに送っていない状態でなければならな い。さもなければ、それはレスポンスを崩壊させる危険を冒す。そのため、 WSGI はアプリケーションがエラーメッセージを送るか、または自動的に中止さ れることを許可するための仕組みを提供する: start_response への exc_info 引数。これは、その使用に関する例である:

try:
    # regular application code here
    status = "200 Froody"
    response_headers = [("content-type", "text/plain")]
    start_response(status, response_headers)
    return ["normal body goes here"]
except:
    # XXX should trap runtime issues like MemoryError, KeyboardInterrupt
    #     in a separate handler before this bare 'except:'...
    status = "500 Oops"
    response_headers = [("content-type", "text/plain")]
    start_response(status, response_headers, sys.exc_info())
    return ["error body goes here"]
If no output has been written when an exception occurs, the call to start_response will return normally, and the application will return an error body to be sent to the browser. However, if any output has already been sent to the browser, start_response will reraise the provided exception. This exception should not be trapped by the application, and so the application will abort. The server or gateway can then trap this (fatal) exception and abort the response.

例外が起こったとき、出力が全く書き出されていない場合は、 start_response への呼び出しは正常に戻る。そして、アプリケーションは ブラウザに送られるエラー本体を返すだろう。しかし、既に何らかの出力をブ ラウザに送った後なら、 start_response は提供された例外を再送出する。 アプリケーションは、この例外を捕捉すべきでない (should not)。そして、 アプリケーションは異常終了 (abort) するだろう。そして、サーバまたはゲー トウェイは、この (致命的) 例外を捕捉して、レスポンスを中止することがで きる。

Servers should trap and log any exception that aborts an application or the iteration of its return value. If a partial response has already been written to the browser when an application error occurs, the server or gateway may attempt to add an error message to the output, if the already-sent headers indicate a text/* content type that the server knows how to modify cleanly.

サーバは、アプリケーションまたはアプリケーションの戻り値のイテレーショ ンを中止するどんな例外も捕捉して、ログに出力すべきである (should)。 アプリケーションエラーが起こるとき、レスポンスの一部が既にブラウザに書 き出されている場合、サーバまたはゲートウェイが、出力にエラーメッセージ を加えようと試みてもよい (may)。これは、既に送られたヘッダーが text/* content type を示し、サーバがそれをどのように安全に変更する かを知っている場合に限る。

Some middleware may wish to provide additional exception handling services, or intercept and replace application error messages. In such cases, middleware may choose to not re-raise the exc_info supplied to start_response, but instead raise a middleware-specific exception, or simply return without an exception after storing the supplied arguments. This will then cause the application to return its error body iterable (or invoke write()), allowing the middleware to capture and modify the error output. These techniques will work as long as application authors:

ミドルウェアによっては、追加の例外処理サービスを提供したり、アプリケー ションエラーメッセージを傍受して、置き換えることを望むかもしれない。そ のような場合、ミドルウェアは、 start_response に渡された exc_info を再送出 しない ことを選ぶかもしれない。代わりにミドル ウェア特有の例外を送出するか、または提供された引数を格納した後に例外な しで単に戻るだろう。これによって、次に、アプリケーションはエラー本体の iterable を返し (または write() を呼び出し)、ミドルウェアがエラー出 力を得て、変更するのを許容する。これらのテクニックは、アプリケーション 作者が次のことを守る場合に動く:

  1. Always provide exc_info when beginning an error response
  2. Never trap errors raised by start_response when exc_info is being provided
  1. エラーレスポンスの開始時に常に exc_info を提供する
  2. exc_info が提供されているときに、 start_response によって送 出されたエラーを捕捉しない

HTTP 1.1 Expect/Continue

Servers and gateways that implement HTTP 1.1 must provide transparent support for HTTP 1.1’s “expect/continue” mechanism. This may be done in any of several ways:

HTTP 1.1 を実装するサーバおよびゲートウェイは、HTTP 1.1 の “expect/continue” メカニズムの透過的なサポートを提供しなければならない (must)。これはいくつかの方法で行うことができる:

  1. Respond to requests containing an Expect: 100-continue request with an immediate “100 Continue” response, and proceed normally.
  1. Expect: 100-continue リクエストを含むリクエストに対して即座に “100 continue” レスポンスを返し、あとは通常通り処理を続ける。
  1. Proceed with the request normally, but provide the application with a wsgi.input stream that will send the “100 Continue” response if/when the application first attempts to read from the input stream. The read request must then remain blocked until the client responds.
  1. 通常通りリクエストを処理する。ただし、アプリケーションが最初に入力ス トリームから読むことを試みるならそのときに、”100 Continue”レスポンス を送信する wsgi.input ストリームをアプリケーションに渡す。そして、 読み出された要求は、クライアントが応答するまで、ブロックされたままで 残らなければならない。
  1. Wait until the client decides that the server does not support expect/continue, and sends the request body on its own. (This is suboptimal, and is not recommended.)
  1. クライアントが、サーバが expect/continue をサポートしないと決定する まで待ち、その後自分自身のリクエスト本体を送る。 (これは準最適であり、 推奨されない)
Note that these behavior restrictions do not apply for HTTP 1.0 requests, or for requests that are not directed to an application object. For more information on HTTP 1.1 Expect/Continue, see RFC 2616, sections 8.2.3 and 10.1.1.

これらの振舞いの制限は、HTTP 1.0 リクエストに対して、またはアプリケーショ ンオブジェクトに向けられていないリクエストに対しては適用されないことに 注意。HTTP1.1 Expect/Continue の詳しい情報に関しては、RFC 2616 セクショ ン 8.2.3、および 10.1.1 を参照。

Other HTTP Features

その他の HTTP 機能

In general, servers and gateways should “play dumb” and allow the application complete control over its output. They should only make changes that do not alter the effective semantics of the application’s response. It is always possible for the application developer to add middleware components to supply additional features, so server/gateway developers should be conservative in their implementation. In a sense, a server should consider itself to be like an HTTP “gateway server”, with the application being an HTTP “origin server”. (See RFC 2616, section 1.3, for the definition of these terms.)

一般に、サーバとゲートウェイは、出力に関して沈黙を守り、アプリケーショ ンに完全なコントロールを許すべきである。それらは、アプリケーションのレ スポンスの有効な意味論を変更しない変更をだけを行うべきである。アプリケー ション開発者は、いつでも付加的な機能を提供するためにミドルウェアのコン ポーネントを加えことができる。そのため サーバ/ゲートウェイ開発者は、彼 らの実装に関して保守的であるべきである。ある意味でサーバは、それ自体が HTTP 「ゲートウェイサーバ」のようなものと考えるべきである。それは HTTP 「オリジナルサーバ」であるアプリケーションを持っている。 (これらの用語 の定義に関して、RFC 2616 セクション 1.3 を参照。)

However, because WSGI servers and applications do not communicate via HTTP, what RFC 2616 calls “hop-by-hop” headers do not apply to WSGI internal communications. WSGI applications must not generate any “hop-by-hop” headers [4], attempt to use HTTP features that would require them to generate such headers, or rely on the content of any incoming “hop-by-hop” headers in the environ dictionary. WSGI servers must handle any supported inbound “hop-by-hop” headers on their own, such as by decoding any inbound Transfer-Encoding, including chunked encoding if applicable.

しかしながら、 WSGI サーバとアプリケーションは HTTP 通信をしないので、 RFC 2616 で “hop-by-hop” ヘッダと呼ばれているものを WSGI の内部の通信に は適用しない。 WSGI アプリケーションは “hop-by-hop”ヘッダー [4] を内部 で生成したり、そのようなヘッダーを生成することを必要とする HTTP 機能を 使用することを試みたり、または入力される environ 辞書の中の “hop-by-hop”ヘッダーの内容も信頼してはならない (must not)。 WSGI サー バは、サポートしている “hop-by-hop” ヘッダの入力を、それ自身で処理しな ければならない (must)。例えば、可能なら chunked encoding を含む Transfer-Encoding をデコードすることによって。

Applying these principles to a variety of HTTP features, it should be clear that a server may handle cache validation via the If-None-Match and If-Modified-Since request headers and the Last-Modified and ETag response headers. However, it is not required to do this, and the application should perform its own cache validation if it wants to support that feature, since the server/gateway is not required to do such validation.

これらの原則をさまざまな HTTP 機能に適用すると、サーバが If-None-MatchIf-Modified-Since リクエストヘッダと、 Last-Modified および ETag レスポンスヘッダを通してキャッシュ・ バリデーションを扱ってもよい (may) ことは明確であるべきである。しか しながら、このようにする必要はなく、アプリケーションがこの特徴をサポー トしたいなら、それ自身のキャッシュ・バリデーションを実行するべきである (should)。なぜなら、サーバ/ゲートウェイがそのようなバリデーションを する必要はないので。

Similarly, a server may re-encode or transport-encode an application’s response, but the application should use a suitable content encoding on its own, and must not apply a transport encoding. A server may transmit byte ranges of the application’s response if requested by the client, and the application doesn’t natively support byte ranges. Again, however, the application should perform this function on its own if desired.

同様に、サーバはアプリケーションのレスポンスを再エンコード、または transport-encode してもよい (may) が、アプリケーションはそれ自身で 適当な content encoding を使用すべきであり (should)、 transport encoding を適用してはならない (must not)。アプリケーションがバイト 範囲をネイティブにサポートしないなら、サーバはクライアントの要求に応じ てアプリケーションのレスポンスのバイト範囲を伝えてもよい (may)。し かし、繰り返すが、必要ならアプリケーション自身でこの機能を実行すべきで ある (should)。

Note that these restrictions on applications do not necessarily mean that every application must reimplement every HTTP feature; many HTTP features can be partially or fully implemented by middleware components, thus freeing both server and application authors from implementing the same features over and over again.

これらのアプリケーションに対する制限が、必ずしもあらゆるアプリケーショ ンはあらゆる HTTP 機能を再実装しなければならないということを意味するわ けではないことに注意。多くの HTTP 機能は、ミドルウェアコンポーネントで 部分的または完全に実装することができる。その結果、サーバとアプリケーショ ンの作者の両方が、同じ機能を幾重にも実装することから解放される。

Thread Support

スレッドサポート

Thread support, or lack thereof, is also server-dependent. Servers that can run multiple requests in parallel, should also provide the option of running an application in a single-threaded fashion, so that applications or frameworks that are not thread-safe may still be used with that server.

スレッドサポート、あるいはその欠如もまた、サーバ依存である。複数の要求 を並列に実行することができるサーバは、スレッド・セーフでないアプリケー ションまたはフレームワークを依然としてそのサーバと共に使用できるように、 シングルスレッド方式でアプリケーションを実行するオプションも提供すべき である (should)。

Implementation/Application Notes

実装/適用上の注意

Server Extension APIs

サーバ拡張 API

Some server authors may wish to expose more advanced APIs, that application or framework authors can use for specialized purposes. For example, a gateway based on mod_python might wish to expose part of the Apache API as a WSGI extension.

サーバ作者の中には、アプリケーションまたはフレームワークの作者が特定の 目的のために使用することができる、より高度な API を公開したいと考えるか もしれない。例えば、 mod_python に基づくゲートウェイは WSGI 拡張と して Apache API の一部を公開したいと考えるかもしれない。

In the simplest case, this requires nothing more than defining an environ variable, such as mod_python.some_api. But, in many cases, the possible presence of middleware can make this difficult. For example, an API that offers access to the same HTTP headers that are found in environ variables, might return different data if environ has been modified by middleware.

最も簡単な場合では、これには mod_python.some_api などの environ 変数を定義することだけが必要とされる。しかし、多くの場合、 ミドルウェアの存在の可能性によって、これが難しくなる場合がある。例えば、 environ 変数で見つけられる同じ HTTP ヘッダへのアクセスを提供する API は、 environ がミドルウェアによって変更されたなら異なったデータ を返すかもしれない。

In general, any extension API that duplicates, supplants, or bypasses some portion of WSGI functionality runs the risk of being incompatible with middleware components. Server/gateway developers should not assume that nobody will use middleware, because some framework developers specifically intend to organize or reorganize their frameworks to function almost entirely as middleware of various kinds.

一般に、 WSGI の機能性の何らかの部分を複製したり、置き換えたり、または 迂回させたりするどんな拡張 API も、ミドルウェアコンポーネントと非互換で あるという危険を冒す。サーバ/ゲートウェイ開発者は、だれもミドルウェアを 使用しないと仮定すべきで ない 。なぜなら、何人かのフレームワークの開 発者が、彼らのフレームワークを様々な種類のミドルウェアとしてほぼ完全に 機能するように構成、または再構成することを具体的に予定しているからだ。

So, to provide maximum compatibility, servers and gateways that provide extension APIs that replace some WSGI functionality, must design those APIs so that they are invoked using the portion of the API that they replace. For example, an extension API to access HTTP request headers must require the application to pass in its current environ, so that the server/gateway may verify that HTTP headers accessible via the API have not been altered by middleware. If the extension API cannot guarantee that it will always agree with environ about the contents of HTTP headers, it must refuse service to the application, e.g. by raising an error, returning None instead of a header collection, or whatever is appropriate to the API.

したがって、最大の互換性を提供するためには、何らかの WSGI の機能性を置 き換える拡張 API を提供するサーバおよびゲートウェイは、それらが置き換え る API の一部を使用して呼び出すことができるように、それらの API を設計 しなければならない (must)。例えば、 HTTP リクエストヘッダーにアクセ スする拡張 API は、アプリケーションに現在の environ を渡すように要 求して、サーバ/ゲートウェイが API を通してアクセスできる HTTP ヘッダが ミドルウェアによって変更されていないことを検証できるようにしなければな らない。拡張 API が HTTP ヘッダの内容に関して常に environ に同調す ることを保証できないなら、アプリケーションへのサービスを拒否しなければ ならない。例えば、エラーを送出したり、ヘッダーの集合の代わりに None を返したり、または API に適切なことなら何でもすることによって。

Similarly, if an extension API provides an alternate means of writing response data or headers, it should require the start_response callable to be passed in, before the application can obtain the extended service. If the object passed in is not the same one that the server/gateway originally supplied to the application, it cannot guarantee correct operation and must refuse to provide the extended service to the application.

同様に、拡張 API がレスポンスデータまたはヘッダーを出力する代替の手段を 提供するなら、アプリケーションが拡張サービスを得ることができる前に start_response callable が渡されることを必要とすべきである。渡され たオブジェクトがサーバ/ゲートウェイが元々アプリケーションに提供したもの と同じでなければ、正しい操作を保証することができないので、アプリケーショ ンへの拡張サービスを提供することを拒否しなければならない。

These guidelines also apply to middleware that adds information such as parsed cookies, form variables, sessions, and the like to environ. Specifically, such middleware should provide these features as functions which operate on environ, rather than simply stuffing values into environ. This helps ensure that information is calculated from environ after any middleware has done any URL rewrites or other environ modifications.

これらのガイドラインは environ に情報 – 例えば、解析済みの Cookie や、フォーム変数、セッション、および同様のもの – を加えるミドルウェア にも適用される。明らかに、そのようなミドルウェアはこれらの特徴を、単に environ に値を詰めるのではなく、 environ に対して働く関数として 提供するべきである。これによって、あらゆるミドルウェアが URL 書き直しや 他の environ 変更をした 後の environ から情報が計算されることを 確実にする。

It is very important that these “safe extension” rules be followed by both server/gateway and middleware developers, in order to avoid a future in which middleware developers are forced to delete any and all extension APIs from environ to ensure that their mediation isn’t being bypassed by applications using those extensions!

サーバ/ゲートウェイとミドルウェア開発者の両方がこれらの「安全な拡張」規 則に従うのは非常に重要である。ミドルウェア開発者が拡張 API を使用してい るアプリケーションから自身の提供する機能が迂回されないことを保証するた めにやむを得ず environ からありとあらゆる拡張 API を削除する未来を 避けるために!

Application Configuration

アプリケーション設定

This specification does not define how a server selects or obtains an application to invoke. These and other configuration options are highly server-specific matters. It is expected that server/gateway authors will document how to configure the server to execute a particular application object, and with what options (such as threading options).

この仕様は、サーバが呼び出すべきアプリケーションをどのように選択または 取得するかについて定義しない。これらの、そして他の設定オプションは極め てサーバ特有の問題である。サーバ/ゲートウェイ作者は、特定のアプリケーショ ンオブジェクトを実行するためにどのように、また何のオプション (スレッド オプションなどの) でサーバを設定するのかを文書化することが期待される。

Framework authors, on the other hand, should document how to create an application object that wraps their framework’s functionality. The user, who has chosen both the server and the application framework, must connect the two together. However, since both the framework and the server now have a common interface, this should be merely a mechanical matter, rather than a significant engineering effort for each new server/framework pair.

その一方で、フレームワークの作者はフレームワークの機能性を包含するアプ リケーションオブジェクトの作成方法を文書化すべきである。ユーザ (彼らは サーバとアプリケーションフレームワークの両方を選んだ) は、その 2つを 1 つに接続しなければならない。しかしながら、現在、フレームワークとサーバ の両方には一般的なインタフェースがあるので、これは、それぞれの新しいサー バ/フレームワークの組に対する重大な工学的努力というより、単に機械的な問 題だろう。

Finally, some applications, frameworks, and middleware may wish to use the environ dictionary to receive simple string configuration options. Servers and gateways should support this by allowing an application’s deployer to specify name-value pairs to be placed in environ. In the simplest case, this support can consist merely of copying all operating system-supplied environment variables from os.environ into the environ dictionary, since the deployer in principle can configure these externally to the server, or in the CGI case they may be able to be set via the server’s configuration files.

最後に、アプリケーション、フレームワーク、およびミドルウェアの中には、 簡単な文字列設定オプションを受け取るために environ 辞書を使用したい と考えるものがあるかもしれない。サーバとゲートウェイは、アプリケーショ ンの配布者が environ に置かれるべき名前-値の組を指定できるようにす ることによって、これをサポートすべきである (should)。最も簡単な場合 では、このサポートは単に OS に提供されたすべての環境変数を os.environ から environ 辞書にコピーすることで成り立つ。なぜな ら、原則として配布者は外部的にこれらをサーバに構成することができるか、 または CGI の場合ではサーバの構成ファイルで設定することができるので。

Applications should try to keep such required variables to a minimum, since not all servers will support easy configuration of them. Of course, even in the worst case, persons deploying an application can create a script to supply the necessary configuration values:

アプリケーションは、そのような必要な変数を最小に抑えようとすべきである (should)。なぜなら、すべてのサーバがそれらの簡単な構成をサポートす るというわけではないので。もちろん、最悪の場合でも、アプリケーションを 配布する人々は必要な設定値を提供するためのスクリプトを作成することがで きる:

from the_app import application

def new_app(environ, start_response):
    environ['the_app.configval1'] = 'something'
    return application(environ, start_response)
But, most existing applications and frameworks will probably only need a single configuration value from environ, to indicate the location of their application or framework-specific configuration file(s). (Of course, applications should cache such configuration, to avoid having to re-read it upon each invocation.)

しかし、既存のアプリケーションやフレームワークは、おそらくただ一つの設 定値を、それらのアプリケーションまたはフレームワーク特有の構成ファイル の位置を示すために environ から必要とするだろう。 (もちろん、アプリ ケーションは起動される度にそれを再読み込みしなければならないのを避ける ために、そのような設定をキャッシュすべきである。)

URL Reconstruction

URL 再構築

If an application wishes to reconstruct a request’s complete URL, it may do so using the following algorithm, contributed by Ian Bicking:

アプリケーションがリクエストの完全な URL を再構築したいなら、Ian Bicking によって寄稿された以下のアルゴリズムが使用できるかもしれない:

from urllib import quote
url = environ['wsgi.url_scheme']+'://'

if environ.get('HTTP_HOST'):
    url += environ['HTTP_HOST']
else:
    url += environ['SERVER_NAME']

    if environ['wsgi.url_scheme'] == 'https':
        if environ['SERVER_PORT'] != '443':
           url += ':' + environ['SERVER_PORT']
    else:
        if environ['SERVER_PORT'] != '80':
           url += ':' + environ['SERVER_PORT']

url += quote(environ.get('SCRIPT_NAME', ''))
url += quote(environ.get('PATH_INFO', ''))
if environ.get('QUERY_STRING'):
    url += '?' + environ['QUERY_STRING']
Note that such a reconstructed URL may not be precisely the same URI as requested by the client. Server rewrite rules, for example, may have modified the client’s originally requested URL to place it in a canonical form.

そのような再構築された URL が、クライアントに要求された URI と正確に同 じではないかもしれないことに注意。例えば、サーバによる URL 書き換え規則 は、元々クライアントが要求した URL を標準形になるように変更したかもしれ ない。

Supporting Older (<2.2) Versions of Python

古い (<2.2) Python のサポート

Some servers, gateways, or applications may wish to support older (<2.2) versions of Python. This is especially important if Jython is a target platform, since as of this writing a production-ready version of Jython 2.2 is not yet available.

いくつかのサーバ、ゲートウェイ、またはアプリケーションでは、古い Python のバージョンをサポートしたいと考えるかもしれない。これは Jython が対象プラットホームであるなら特に重要である。なぜなら、これを書いてい る時点では Jython 2.2 の production-ready のバージョンはまだ利用可能で ないからだ。

For servers and gateways, this is relatively straightforward: servers and gateways targeting pre-2.2 versions of Python must simply restrict themselves to using only a standard “for” loop to iterate over any iterable returned by an application. This is the only way to ensure source-level compatibility with both the pre-2.2 iterator protocol (discussed further below) and “today’s” iterator protocol (see PEP 234).

サーバとゲートウェイに関しては、これは比較的簡単である: Python 2.2 以下 のバージョンを対象とするサーバとゲートウェイは、単にアプリケーションで 返されたあらゆる iterable に対して標準の “for” ループだけを使用して繰り 返しを行うように制限しなければならない。これが、 2.2 以下のイテレータ・ プロトコル (さらに以下で議論する) と、「今日的な」イテレータ・プロトコ ル (PEP 234 を参照) の両方に対して、ソースレベルの互換性を確実にする唯 一の方法である。

(Note that this technique necessarily applies only to servers, gateways, or middleware that are written in Python. Discussion of how to use iterator protocol(s) correctly from other languages is outside the scope of this PEP.)

(このテクニックは、Python で書かれているサーバ、ゲートウェイ、またはミ ドルウェアだけに適用する必要があることに注意。他の言語でイテレータ・プ ロトコルをどのように正しく使用するかに関する議論は、このPEPの範囲外であ る。)

For applications, supporting pre-2.2 versions of Python is slightly more complex:

アプリケーションにおいて、Python pre-2.2 バージョンをサポートするのは、 わずかに複雑である:

  • You may not return a file object and expect it to work as an iterable, since before Python 2.2, files were not iterable. (In general, you shouldn’t do this anyway, because it will perform quite poorly most of the time!) Use wsgi.file_wrapper or an application-specific file wrapper class. (See Optional Platform-Specific File Handling for more on wsgi.file_wrapper, and an example class you can use to wrap a file as an iterable.)
  • ファイルオブジェクトを返して、それが iterable として働くと期待するこ とはできない。なぜなら、Python 2.2 以前では、ファイルは iterable では なかったので。 (大抵は非常に性能が悪いので、一般には、とにかくあなた はこれをするべきではない!) wsgi.file_wrapper またはアプリケーショ ン特有のファイルラッパーのクラスを使用する。 (wsgi.file_wrapper についての詳しい情報と、ファイルを iterable としてラップするために使 用できるクラスの例については、 Optional Platform-Specific File Handling を参照。)
  • If you return a custom iterable, it must implement the pre-2.2 iterator protocol. That is, provide a __getitem__ method that accepts an integer key, and raises IndexError when exhausted. (Note that built-in sequence types are also acceptable, since they also implement this protocol.)
  • もしカスタムの iterable を返すなら、それは pre-2.2 イテレータ・プロト コルを実装しなければならない (must)。すなわち、整数キーを受け取っ て、もしイテレーションが終了していたら IndexError を raise する __getitem__ メソッドを提供する。 (built-inのシーケンスタイプもこ のプロトコルを実装しているので、それらも許容されることに注意。)
Finally, middleware that wishes to support pre-2.2 versions of Python, and iterates over application return values or itself returns an iterable (or both), must follow the appropriate recommendations above.

最後に、ミドルウェアが Python pre-2.2 バージョンのサポートを希望してい て、アプリケーション戻り値をイテレートするか、それ自体が iterable を返 す (またはその両方の) 場合、上の適切な推奨に従わなければならない

(Note: It should go without saying that to support pre-2.2 versions of Python, any server, gateway, application, or middleware must also use only language features available in the target version, use 1 and 0 instead of True and False, etc.)

(言うまでもなく、Python pre-2.2 バージョンをサポートするためにはどんな サーバ、ゲートウェイ、アプリケーション、またはミドルウェアも、対象バー ジョンで利用可能な言語機能だけを使用しなければならない。 TrueFalse の代わりに 1 と 0 を使用するなど)

Optional Platform-Specific File Handling

任意のプラットフォーム特有なファイルの扱い

Some operating environments provide special high-performance file- transmission facilities, such as the Unix sendfile() call. Servers and gateways may expose this functionality via an optional wsgi.file_wrapper key in the environ. An application may use this “file wrapper” to convert a file or file-like object into an iterable that it then returns, e.g.:

いくつかのオペレーティング環境は、Unixの sendfile() 呼び出しなどの 特別な高性能ファイル転送機能を提供する。サーバおよびゲートウェイは、 environ の中のオプショナルな wsgi.file_wrapper キーを通して、こ の機能を公開してもよい (may)。アプリケーションは、例えばファイルま たは file-like オブジェクトをその次に返す iterable に変換するのに、この 「ファイルラッパー」を使用してもよい (may):

if 'wsgi.file_wrapper' in environ:
    return environ['wsgi.file_wrapper'](filelike, block_size)
else:
    return iter(lambda: filelike.read(block_size), '')
If the server or gateway supplies wsgi.file_wrapper, it must be a callable that accepts one required positional parameter, and one optional positional parameter. The first parameter is the file-like object to be sent, and the second parameter is an optional block size “suggestion” (which the server/gateway need not use). The callable must return an iterable object, and must not perform any data transmission until and unless the server/gateway actually receives the iterable as a return value from the application. (To do otherwise would prevent middleware from being able to interpret or override the response data.)

サーバまたはゲートウェイが wsgi.file_wrapper を提供するなら、それは、 1つの必須の位置パラメタと 1つの任意の位置パラメタを受け取る callable で なければならない。最初のパラメタは送られる file-like オブジェクトであり、 2番目のパラメタは任意のブロック・サイズ “suggestion” (サーバ/ゲートウェ イが使用する必要はない) である。その callable は、iterable オブジェクト を返さなければならない (must)。そして、サーバ/ゲートウェイが実際に アプリケーションからの戻り値として iterable を受け取るまで、どんなデー タ伝送も実行してはならない (must not) (そうしないと、ミドルウェアが レスポンスデータを解釈またはオーバーライドすることが阻害される)

To be considered “file-like”, the object supplied by the application must have a read() method that takes an optional size argument. It may have a close() method, and if so, the iterable returned by wsgi.file_wrapper must have a close() method that invokes the original file-like object’s close() method. If the “file-like” object has any other methods or attributes with names matching those of Python built-in file objects (e.g. fileno()), the wsgi.file_wrapper may assume that these methods or attributes have the same semantics as those of a built-in file object.

“file-like” と見なすために、アプリケーションで提供されたオブジェクトは、 任意のサイズ引数を受け取る read() メソッドを持っていなければならな い。それは close() メソッドを持っていてもよく (may)、もしそうな ら wsgi.file_wrapper によって返された iterable は、オリジナルの file-like オブジェクトの close() メソッドを呼び出す close() メ ソッドを持っていなければならない (must)。 file-like オブジェクトが 他の Python built-in のファイルオブジェクトと名前が一致するメソッドまた は属性 (例えば fileno()) を持っている場合、 wsgi.file_wrapper は、これらのメソッドまたは属性が built-in のファイルオブジェクトのもの と同じ意味論を持つと仮定してもよい (may)。

The actual implementation of any platform-specific file handling must occur after the application returns, and the server or gateway checks to see if a wrapper object was returned. (Again, because of the presence of middleware, error handlers, and the like, it is not guaranteed that any wrapper created will actually be used.)

どんなプラットホーム特有のファイル取り扱いの実際の実装も、アプリケーショ ンが戻った 後に 起こらなければならない。そして、サーバまたはゲート ウェイは、ラッパーオブジェクトが返されたかどうかを確かめる。 (繰り返す が、ミドルウェアやエラーハンドラ、および同様のものの存在のために、作成 されたどんなラッパーも実際に使用されるかどうかは保証されない。)

Apart from the handling of close(), the semantics of returning a file wrapper from the application should be the same as if the application had returned iter(filelike.read, ''). In other words, transmission should begin at the current position within the “file” at the time that transmission begins, and continue until the end is reached.

close() の取り扱いは別として、アプリケーションからファイルラッパー を返すことの意味は、アプリケーションが iter(filelike.read, '') を返 したのと同じであるべきである。言い換えれば、転送が始まる時の「ファイル」 の中の現在の位置から転送が始まり、端に達するまで続くべきである。

Of course, platform-specific file transmission APIs don’t usually accept arbitrary “file-like” objects. Therefore, a wsgi.file_wrapper has to introspect the supplied object for things such as a fileno() (Unix-like OSes) or a java.nio.FileChannel (under Jython) in order to determine if the file-like object is suitable for use with the platform-specific API it supports.

もちろん、プラットホーム特有のファイル転送 API は通常、任意の “file-like” オブジェクトを受け入れるわけではない。したがって、 wsgi.file_wrapper は、サポートするプラットホーム特有の API に対して file-like オブジェクトを使用するのが適切かどうかを決定するために、提供 されたオブジェクトの fileno() (unix のような OS) や java.nio.FileChannel (Jython の元で) などを introspect しなければな らない。

Note that even if the object is not suitable for the platform API, the wsgi.file_wrapper must still return an iterable that wraps read() and close(), so that applications using file wrappers are portable across platforms. Here’s a simple platform-agnostic file wrapper class, suitable for old (pre 2.2) and new Pythons alike:

ファイルラッパーを使用するアプリケーションがプラットホームを越えて移植 性があるように、オブジェクトがプラットホーム API にとって適切で なくて もwsgi.file_wrapperread()close() をラップする iterable を返さなければならない (must) ことに注意。これは、古い (2.2 以前の) Python と新しい Pythons で同じように適切な、プラットホーム によらない簡単なファイルラッパーのクラスである:

class FileWrapper:

    def __init__(self, filelike, blksize=8192):
        self.filelike = filelike
        self.blksize = blksize
        if hasattr(filelike, 'close'):
            self.close = filelike.close

    def __getitem__(self, key):
        data = self.filelike.read(self.blksize)
        if data:
            return data
        raise IndexError
and here is a snippet from a server/gateway that uses it to provide access to a platform-specific API:

そしてこれは、プラットホーム特有の API へのアクセスを提供するサーバ/ゲー トウェイで使われているコード片である:

environ['wsgi.file_wrapper'] = FileWrapper
result = application(environ, start_response)

try:
    if isinstance(result, FileWrapper):
        # check if result.filelike is usable w/platform-specific
        # API, and if so, use that API to transmit the result.
        # If not, fall through to normal iterable handling
        # loop below.

    for data in result:
        # etc.

finally:
    if hasattr(result, 'close'):
        result.close()

Questions and Answers

質疑応答

  1. Why must environ be a dictionary? What’s wrong with using a subclass?
  1. environ はなぜ辞書でなければならないのか? サブクラスを使用すると 何が問題なのか?

    The rationale for requiring a dictionary is to maximize portability between servers. The alternative would be to define some subset of a dictionary’s methods as being the standard and portable interface. In practice, however, most servers will probably find a dictionary adequate to their needs, and thus framework authors will come to expect the full set of dictionary features to be available, since they will be there more often than not. But, if some server chooses not to use a dictionary, then there will be interoperability problems despite that server’s “conformance” to spec. Therefore, making a dictionary mandatory simplifies the specification and guarantees interoperabilty.

    辞書を必要とする理由は、サーバ間の移植可能性を最大にすることである。 代替手段は、辞書のメソッドの何らかの部分集合を、標準的な、そして移植 性のあるインタフェースとして定義することだろう。しかしながら、実際に はおそらく、ほとんどのサーバが、彼らの必要性に辞書が適切であることが わかるだろう。そして、その結果、フレームワーク作者は完全なセットの辞 書機能が利用可能であると予想するようになるだろう。なぜなら、しばしば それらがそこにあるので。しかし、何らかのサーバが辞書を使わ ない こ とを選ぶと、そのサーバは仕様に準拠しているにもかかわらず、相互運用性 の問題が生じるだろう。したがって、辞書を必須にすると、仕様が簡素化さ れ、相互運用性が保証される。

    Note that this does not prevent server or framework developers from offering specialized services as custom variables inside the environ dictionary. This is the recommended approach for offering any such value-added services.

    これは、サーバまたはフレームワーク開発者がカスタム変数として特殊化し たサービスを environ 辞書の 内部に 提供するのを妨げないことに 注意。これは、そのような付加価値サービスを提供することに対するお勧め のアプローチである。

  1. Why can you call write() and yield strings/return an iterable? Shouldn’t we pick just one way?
  1. なぜ write() を呼び出すことができ、 かつ 文字列を yield する /iterable を返すこともできるのか? ただ 1つの方法を選ぶべきではないか?

    If we supported only the iteration approach, then current frameworks that assume the availability of “push” suffer. But, if we only support pushing via write(), then server performance suffers for transmission of e.g. large files (if a worker thread can’t begin work on a new request until all of the output has been sent). Thus, this compromise allows an application framework to support both approaches, as appropriate, but with only a little more burden to the server implementor than a push-only approach would require.

    もしイテレーションのアプローチだけをサポートしたなら、 “push” が利用 できることを仮定する現在のフレームワークが被害を受ける。しかし、 write() を通した push だけをサポートするなら、例えば大きいファイ ルの転送でサーバ性能に影響がある (ワーカースレッドが出力のすべてを送 るまで新しい要求に対する仕事を始めることができないなら)。したがって、 この妥協によってアプリケーション・フレームワークが必要に応じて両方の アプローチをサポートできるようになり、しかし、サーバ作成者への負荷は push だけのアプローチで必要になるよりもほんの少し増えるようになる。

  1. What’s the close() for?
  1. close() は何のためにあるのか?

    When writes are done during the execution of an application object, the application can ensure that resources are released using a try/finally block. But, if the application returns an iterable, any resources used will not be released until the iterable is garbage collected. The close() idiom allows an application to release critical resources at the end of a request, and it’s forward-compatible with the support for try/finally in generators that’s proposed by PEP 325.

    アプリケーション・オブジェクトの実行の間に出力が終了した場合、アプリ ケーションは try/finally ブロックを使ってリソースが確実に解放される ようにすることができる。しかし、アプリケーションが iterable を返すと、 どんなリソースも iterable がガベージコレクトされるまで解放されない。 close() イディオムは、アプリケーションがリクエストの終わりで重要 な資源を解放できるようにする。そして、PEP 325 で提案されたジェネレー タの try/finally サポートの前方互換性をアプリケーションに許容する。

  1. Why is this interface so low-level? I want feature X! (e.g. cookies, sessions, persistence, ...)
  1. なぜこのインタフェースはこんなに低レベルなのか? 機能 X (Cookie, セッ ション、永続化、など) が欲しい!

    This isn’t Yet Another Python Web Framework. It’s just a way for frameworks to talk to web servers, and vice versa. If you want these features, you need to pick a web framework that provides the features you want. And if that framework lets you create a WSGI application, you should be able to run it in most WSGI-supporting servers. Also, some WSGI servers may offer additional services via objects provided in their environ dictionary; see the applicable server documentation for details. (Of course, applications that use such extensions will not be portable to other WSGI-based servers.)

    これは Yet Another Python Web フレームワークではない。単にフレームワー クと Web サーバーが会話する方法である。これらの機能が欲しいなら、欲し い機能を提供する Web フレームワークを選ぶ必要がある。そして、そのフレー ムワークで WSGI アプリケーションを作成することができるなら、ほとんど の WSGI をサポートしているサーバでそれを実行することができるはずだ。 また、いくつかの WSGI サーバでは、 environ 辞書に提供されたオブジェ クトを通して追加サービスを提供するかもしれない; 詳細に関して適切なサー バドキュメンテーションを参照のこと。 (もちろん、そのような拡張を使用 するアプリケーションは、他の WSGI ベースのサーバに移植可能ではないだ ろう。)

  1. Why use CGI variables instead of good old HTTP headers? And why mix them in with WSGI-defined variables?
  1. なぜ古き良き HTTP ヘッダの代わりに CGI 変数を使用するのか? そして、 なぜそれらを WSGI-定義の変数の中に混ぜるのか?

    Many existing web frameworks are built heavily upon the CGI spec, and existing web servers know how to generate CGI variables. In contrast, alternative ways of representing inbound HTTP information are fragmented and lack market share. Thus, using the CGI “standard” seems like a good way to leverage existing implementations. As for mixing them with WSGI variables, separating them would just require two dictionary arguments to be passed around, while providing no real benefits.

    既存の多くの Web フレームワークが CGI 仕様に極度に基づいている。そし て既存の Web サーバーは CGI 変数を生成する方法を知っている。対照的に、 入力された HTTP 情報を表す代替の方法は、断片化していて、市場のシェア を欠いている。したがって、 CGI 「標準」を使用するのは、既存の実装を 活用する良い方法のように見える。それらを WSGI 変数に混ぜることに関し て、それらを切り離すのはただ 2つの辞書引数をたらい回しにする必要があ るだけで、何の現実的な利点も提供しないだろう。

  1. What about the status string? Can’t we just use the number, passing in 200 instead of "200 OK"?
  1. ステータス文字列についてはどうか? 数字を使うことはできないか? つまり、 "200 OK" の代わりに 200 を渡す

    Doing this would complicate the server or gateway, by requiring them to have a table of numeric statuses and corresponding messages. By contrast, it is easy for an application or framework author to type the extra text to go with the specific response code they are using, and existing frameworks often already have a table containing the needed messages. So, on balance it seems better to make the application/framework responsible, rather than the server or gateway.

    これをすると、数値の状態と対応するメッセージのテーブルを持つ必要があ るので、サーバまたはゲートウェイが複雑になるだろう。対照的に、アプリ ケーションまたはフレームワーク作者が、使用している特定の応答コードに 伴う付加的なテキストをタイプするのは簡単であり、既存のフレームワーク はしばしば既に必要なメッセージを含むテーブルを持っている。したがって、 バランスの問題で、サーバまたはゲートウェイよりもアプリケーション/フ レームワークが責任を持つ方が良いように思える。

  1. Why is wsgi.run_once not guaranteed to run the app only once?
  1. なぜ wsgi.run_once はアプリケーションが 1度だけ実行されることを 保証しないのか?

    Because it’s merely a suggestion to the application that it should “rig for infrequent running”. This is intended for application frameworks that have multiple modes of operation for caching, sessions, and so forth. In a “multiple run” mode, such frameworks may preload caches, and may not write e.g. logs or session data to disk after each request. In “single run” mode, such frameworks avoid preloading and flush all necessary writes after each request.

    なぜなら、それが単にアプリケーションに対する「通常でない実行への準備」 のための示唆であるからだ。これはキャッシュやセッションなどのための複 数実行モードを持っているアプリケーション・フレームワークのために意図 されている。「複数実行」モードでは、そのようなフレームワークはキャッ シュを事前ロードして、各要求の後では例えばログやセッションデータをディ スクに書かないかもしれない。そのようなフレームワークは、「単一実行」 モードで事前ロードを避けて、各要求の後に必要な書き込みを flush する。

    However, in order to test an application or framework to verify correct operation in the latter mode, it may be necessary (or at least expedient) to invoke it more than once. Therefore, an application should not assume that it will definitely not be run again, just because it is called with wsgi.run_once set to True.

    しかしながら、後者のモードにおいてアプリケーションまたはフレームワー クが正しい動作をするかテストするために、それを一度より多く呼び出すの は、必要 (そして、少なくとも有益) だろう。したがって、アプリケーショ ンは、 wsgi.run_onceTrue にセットされて呼び出されたから といって、それが絶対に再び実行されないと仮定すべきではない。

  1. Feature X (dictionaries, callables, etc.) are ugly for use in application code; why don’t we use objects instead?
  1. 機能 X (辞書、callable、etc.) はアプリケーションコードで使うには醜す ぎる; なぜ代わりにオブジェクトを使わないのか?

    All of these implementation choices of WSGI are specifically intended to decouple features from one another; recombining these features into encapsulated objects makes it somewhat harder to write servers or gateways, and an order of magnitude harder to write middleware that replaces or modifies only small portions of the overall functionality.

    WSGI のこれらの実装上の選択はすべて、一つの機能を他の機能と 分離 するために明確に意図されている; これらの機能をカプセル化オブジェクト に再結合するのは、サーバまたはゲートウェイをいくらか書きにくくして、 さらに全体の機能の一部だけを置き換える、または変更するミドルウェアを 書くことを大幅に困難にする。

    In essence, middleware wants to have a “Chain of Responsibility” pattern, whereby it can act as a “handler” for some functions, while allowing others to remain unchanged. This is difficult to do with ordinary Python objects, if the interface is to remain extensible. For example, one must use __getattr__ or __getattribute__ overrides, to ensure that extensions (such as attributes defined by future WSGI versions) are passed through.

    本質的に、ミドルウェアは “Chain of Responsibility” パターンを必要と する。それは、いくつかの機能のために「ハンドラ」として働く一方で、他 の機能に対してはそのまま残すことを許容する。インタフェースが拡張性を 残すなら、これは普通の Python オブジェクトを処理することが難しい。例 えば、拡張 (将来の WSGI バージョンによって定義された属性などの) が通 過することを保証するためには、 __getattr__ または __getattribute__ のオーバーライドを使用しなければならない。

    This type of code is notoriously difficult to get 100% correct, and few people will want to write it themselves. They will therefore copy other people’s implementations, but fail to update them when the person they copied from corrects yet another corner case.

    このタイプのコードを100%正しく書くのが難しいのはよく知られている。そ して、わずかな人々しか自分たちでそれを書きたくならないだろう。したがっ て、人々は他の人の実装をコピーするだろうが、元にした実装でさらに別の コーナーケースが修正されたとき、それらはアップデートされないだろう。

    Further, this necessary boilerplate would be pure excise, a developer tax paid by middleware developers to support a slightly prettier API for application framework developers. But, application framework developers will typically only be updating one framework to support WSGI, and in a very limited part of their framework as a whole. It will likely be their first (and maybe their only) WSGI implementation, and thus they will likely implement with this specification ready to hand. Thus, the effort of making the API “prettier” with object attributes and suchlike would likely be wasted for this audience.

    さらに、この必要な定型文は純粋な消費税だろう。ミドルウェア開発者がア プリケーション・フレームワーク開発者のためにわずかにきれいな API を サポートするのに支払った開発者税。しかし、アプリケーション・フレーム ワークの開発者は通常、 WSGIをサポートするために 1つの フレームワーク だけを、そして彼らのフレームワーク全体のとても限定的な部分をアップデー トしている。それがおそらく彼らの最初の (そして多分唯一の) WSGI 実装 であり、彼らはおそらくこの仕様を手の届く範囲で (ready to hand) 実装 するだろう。したがって、 API をオブジェクト属性などに「よりきれいに」 する取り組みは、おそらくこの聴衆によって浪費されるだろう。

    We encourage those who want a prettier (or otherwise improved) WSGI interface for use in direct web application programming (as opposed to web framework development) to develop APIs or frameworks that wrap WSGI for convenient use by application developers. In this way, WSGI can remain conveniently low-level for server and middleware authors, while not being “ugly” for application developers.

    我々は、(Web フレームワーク開発とは対照的に) 直接 Web アプリケーショ ン・プログラミングに使える、よりきれいな (または別の方法で改良された) WSGI インタフェースを望む人々が、アプリケーション開発者によって便利 に使用できるような、 WSGIをラップする API またはフレームワークを開発 するのを奨励する。このように、 WSGI はサーバとミドルウェア作者には便 利に低レベルであるままで残る一方で、アプリケーション開発者には「醜く」 なくなることができる。

Proposed/Under Discussion

提案された/討議中の話題

These items are currently being discussed on the Web-SIG and elsewhere, or are on the PEP author’s “to-do” list:

これらの項目は、現在 Web-SIG 上やほかの場所で議論しているか、または PEP 作者の “to-do” リストにある:

  • Should wsgi.input be an iterator instead of a file? This would help for asynchronous applications and chunked-encoding input streams.
  • wsgi.input はファイルではなくイテレータの方が良いのではないか? そ うすることで、非同期アプリケーションや chunked encoding 入力ストリー ムで役立つだろう。
  • Optional extensions are being discussed for pausing iteration of an application’s output until input is available or until a callback occurs.
  • 入力が利用可能になるか、またはコールバックが起こるまで、アプリケーショ ン出力のイテレーションを中断するためのオプショナルな拡張について議論 されている。
  • Add a section about synchronous vs. asynchronous apps and servers, the relevant threading models, and issues/design goals in these areas.
  • アプリケーションとサーバの同期 vs. 非同期、関連するスレッドモデル、お よびこれらの領域の問題/設計目標に関するセクションを加える。

Acknowledgements

謝辞

Thanks go to the many folks on the Web-SIG mailing list whose thoughtful feedback made this revised draft possible. Especially:

Web-SIG メーリングリスト上のたくさんの仲間に感謝したい。ML上の思慮深い フィードバックによって修正を重ね、このドラフトを書くことができた。特に、 以下の方々には感謝の意を捧げたい:

  • Gregory “Grisha” Trubetskoy, author of mod_python, who beat up on the first draft as not offering any advantages over “plain old CGI”, thus encouraging me to look for a better approach.
  • mod_python の作者である Gregory “Grisha” Trubetskoy は、はじめの ドラフトに対して、「従来のただの CGI (plain old CGI)」と比べてなんら 利点がないと指摘し、私を打ちのめしてくれた。おかげでより良い方法に目 を向ける勇気を得られた。
  • Ian Bicking, who helped nag me into properly specifying the multithreading and multiprocess options, as well as badgering me to provide a mechanism for servers to supply custom extension data to an application.
  • Ian Bicking は、マルチスレッドやマルチプロセスのオプションを適切に定 めるよう、口うるさく言ってくれた。そして、サーバが独自のデータ拡張を アプリケーションに提供するような仕組みを提供するよう、しつこく言って くれた。
  • Tony Lownds, who came up with the concept of a start_response function that took the status and headers, returning a write function. His input also guided the design of the exception handling facilities, especially in the area of allowing for middleware that overrides application error messages.
  • Tony Lownds は、ステータスとヘッダ情報を引数として受け取って write 関数を返す start_response 関数のコンセプトを考え出して くれた。また彼の言葉によって、便利な例外処理の設計、特にアプリケーショ ンのエラーメッセージをミドルウェアが上書きすることを許可するという部 分、が導かれた。
  • Alan Kennedy, whose courageous attempts to implement WSGI-on-Jython (well before the spec was finalized) helped to shape the “supporting older versions of Python” section, as well as the optional wsgi.file_wrapper facility.
  • Alan Kennedy – 勇敢にも (仕様が十分確定する前に) WSGI-on-Jython を実 装しようと試みた – は、 “supporting older versions of Python” セクショ ン、およびオプションの wsgi.file_wrapper 機能を形にするのを助けた。
  • Mark Nottingham, who reviewed the spec extensively for issues with HTTP RFC compliance, especially with regard to HTTP/1.1 features that I didn’t even know existed until he pointed them out.
  • Mark Nottingham は、HTTP RFC の規則に則っているかを広範囲でレビューし てくれた。特に、 HTTP/1.1 の機能の数々は、彼が指摘するまで私は存在す ら知らなかった。

References

参考

[1]The Python Wiki “Web Programming” topic (http://www.python.org/cgi-bin/moinmoin/WebProgramming)
[2]The Common Gateway Interface Specification, v 1.1, 3rd Draft (http://ken.coar.org/cgi/draft-coar-cgi-v11-03.txt)
[3]“Chunked Transfer Coding” – HTTP/1.1, section 3.6.1 (http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.6.1)
[4]“End-to-end and Hop-by-hop Headers” – HTTP/1.1, Section 13.5.1 (http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.5.1)
[5]mod_ssl Reference, “Environment Variables” (http://www.modssl.org/docs/2.8/ssl_reference.html#ToC25)