应用程序对象只是一个接受两个参数的 callable 对象而已. 别把术语 "对象" 误解为真的需要一个实例对象: 一个函数, 方法, 类, 或者实现了 __call__ 方法的实例对象都可以用来作为应用程序对象. 应用程序对象必须能够被重复调用, 因为实际上所有 服务器(除了CGI) 都会发出这样的重复的请求.

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.

(注意: 虽然我们把它说成是一个 "应用程序" 对象, 但也别误解为应用程序开发者会把 WSGI 当一个 web编程API 来用! 我们假定应用程序开发者仍然使用现有的,高层的框架服务来开发他们的应用程序. WSGI 是一个给框架和服务器开发者用的工具, 并且不会提供对应用程序开发者的直接支持.)

(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.)

1. 示例

   1 def simple_app(environ, start_response):
   2     """Simplest possible application object"""
   3     status = '200 OK'
   4     response_headers = [('Content-type','text/plain')]
   5     start_response(status, response_headers)
   6     return ['Hello world!\n']
   7 
   8 
   9 class AppClass:
  10     """Produce the same output, but using a class
  11 
  12     (Note: 'AppClass' is the "application" here, so calling it
  13     returns an instance of 'AppClass', which is then the iterable
  14     return value of the "application callable" as required by
  15     the spec.
  16 
  17     If we wanted to use *instances* of 'AppClass' as application
  18     objects instead, we would have to implement a '__call__'
  19     method, which would be invoked to execute the application,
  20     and we would need to create an instance for use by the
  21     server or gateway.
  22     """
  23 
  24     def __init__(self, environ, start_response):
  25         self.environ = environ
  26         self.start = start_response
  27 
  28     def __iter__(self):
  29         status = '200 OK'
  30         response_headers = [('Content-type','text/plain')]
  31         self.start(status, response_headers)
  32         yield "Hello world!\n"