Back to index

moin  1.9.0~rc2
Public Member Functions | Public Attributes | Static Public Attributes | Properties | Private Member Functions
MoinMoin.support.werkzeug.wrappers.BaseResponse Class Reference
Inheritance diagram for MoinMoin.support.werkzeug.wrappers.BaseResponse:
Inheritance graph
[legend]
Collaboration diagram for MoinMoin.support.werkzeug.wrappers.BaseResponse:
Collaboration graph
[legend]

List of all members.

Public Member Functions

def __init__
def force_type
def from_app
def iter_encoded
def set_cookie
def delete_cookie
def header_list
def is_streamed
def fix_headers
def close
def freeze
def __call__

Public Attributes

 response
 headers
 status
 direct_passthrough

Static Public Attributes

string charset = 'utf-8'
int default_status = 200
string default_mimetype = 'text/plain'

Properties

 status_code
 data = property(_get_data, _set_data, doc=_get_data.__doc__)

Private Member Functions

def _get_status_code
def _set_status_code
def _get_data
def _set_data

Detailed Description

Base response class.  The most important fact about a response object
is that it's a regular WSGI application.  It's initialized with a couple
of response parameters (headers, body, status code etc.) and will start a
valid WSGI response when called with the environ and start response
callable.

Because it's a WSGI application itself processing usually ends before the
actual response is sent to the server.  This helps debugging systems
because they can catch all the exceptions before responses are started.

Here a small example WSGI application that takes advantage of the
response objects::

    from werkzeug import BaseResponse as Response

    def index():
        return Response('Index page')

    def application(environ, start_response):
        path = environ.get('PATH_INFO') or '/'
        if path == '/':
            response = index()
        else:
            response = Response('Not Found', status=404)
        return response(environ, start_response)

Like :class:`BaseRequest` which object is lacking a lot of functionality
implemented in mixins.  This gives you a better control about the actual
API of your response objects, so you can create subclasses and add custom
functionality.  A full featured response object is available as
:class:`Response` which implements a couple of useful mixins.

To enforce a new type of already existing responses you can use the
:meth:`force_type` method.  This is useful if you're working with different
subclasses of response objects and you want to post process them with a
know interface.

Per default the request object will assume all the text data is `utf-8`
encoded.  Please refer to `the unicode chapter <unicode.txt>`_ for more
details about customizing the behavior.

Response can be any kind of iterable or string.  If it's a string
it's considered being an iterable with one item which is the string
passed.  Headers can be a list of tuples or a :class:`Headers` object.

Special note for `mimetype` and `content_type`:  For most mime types
`mimetype` and `content_type` work the same, the difference affects
only 'text' mimetypes.  If the mimetype passed with `mimetype` is a
mimetype starting with `text/` it becomes a charset parameter defined
with the charset of the response object.  In contrast the
`content_type` parameter is always added as header unmodified.

.. versionchanged:: 0.5
   the `direct_passthrough` parameter was added.

:param response: a string or response iterable.
:param status: a string with a status or an integer with the status code.
:param headers: a list of headers or an :class:`Headers` object.
:param mimetype: the mimetype for the request.  See notice above.
:param content_type: the content type for the request.  See notice above.
:param direct_passthrough: if set to `True` :meth:`iter_encoded` is not
                           called before iteration which makes it
                           possible to pass special iterators though
                           unchanged (see :func:`wrap_file` for more
                           details.)

Definition at line 416 of file wrappers.py.


Constructor & Destructor Documentation

def MoinMoin.support.werkzeug.wrappers.BaseResponse.__init__ (   self,
  response = None,
  status = None,
  headers = None,
  mimetype = None,
  content_type = None,
  direct_passthrough = False 
)

Definition at line 488 of file wrappers.py.

00488 
00489                  mimetype=None, content_type=None, direct_passthrough=False):
00490         if response is None:
00491             self.response = []
00492         elif isinstance(response, basestring):
00493             self.response = [response]
00494         else:
00495             self.response = iter(response)
00496         if not headers:
00497             self.headers = Headers()
00498         elif isinstance(headers, Headers):
00499             self.headers = headers
00500         else:
00501             self.headers = Headers(headers)
00502         if content_type is None:
00503             if mimetype is None and 'Content-Type' not in self.headers:
00504                 mimetype = self.default_mimetype
00505             if mimetype is not None:
00506                 mimetype = get_content_type(mimetype, self.charset)
00507             content_type = mimetype
00508         if content_type is not None:
00509             self.headers['Content-Type'] = content_type
00510         if status is None:
00511             status = self.default_status
00512         if isinstance(status, (int, long)):
00513             self.status_code = status
00514         else:
00515             self.status = status
00516         self.direct_passthrough = direct_passthrough


Member Function Documentation

def MoinMoin.support.werkzeug.wrappers.BaseResponse.__call__ (   self,
  environ,
  start_response 
)
Process this response as WSGI application.

:param environ: the WSGI environment.
:param start_response: the response callable provided by the WSGI
               server.

Definition at line 698 of file wrappers.py.

00698 
00699     def __call__(self, environ, start_response):
00700         """Process this response as WSGI application.
00701 
00702         :param environ: the WSGI environment.
00703         :param start_response: the response callable provided by the WSGI
00704                                server.
00705         """
00706         self.fix_headers(environ)
00707         if environ['REQUEST_METHOD'] == 'HEAD':
00708             resp = ()
00709         elif 100 <= self.status_code < 200 or self.status_code in (204, 304):
00710             # no response for 204/304.  the headers are adapted accordingly
00711             # by fix_headers()
00712             resp = ()
00713         elif self.direct_passthrough:
00714             resp = self.response
00715         else:
00716             resp = self.iter_encoded()
00717         start_response(self.status, self.header_list)
00718         return resp
00719 

Here is the call graph for this function:

The string representation of the request body.  Whenever you access
this property the request iterable is encoded and flattened.  This
can lead to unwanted behavior if you stream big data.

Definition at line 584 of file wrappers.py.

00584 
00585     def _get_data(self):
00586         """The string representation of the request body.  Whenever you access
00587         this property the request iterable is encoded and flattened.  This
00588         can lead to unwanted behavior if you stream big data.
00589         """
00590         if not isinstance(self.response, list):
00591             self.response = list(self.response)
        return ''.join(self.iter_encoded())

Here is the call graph for this function:

Definition at line 570 of file wrappers.py.

00570 
00571     def _get_status_code(self):
00572         try:
00573             return int(self.status.split(None, 1)[0])
00574         except ValueError:
            return 0
def MoinMoin.support.werkzeug.wrappers.BaseResponse._set_data (   self,
  value 
) [private]

Definition at line 592 of file wrappers.py.

00592 
00593     def _set_data(self, value):
        self.response = [value]

Definition at line 575 of file wrappers.py.

00575 
00576     def _set_status_code(self, code):
00577         try:
00578             self.status = '%d %s' % (code, HTTP_STATUS_CODES[code].upper())
00579         except KeyError:
            self.status = '%d UNKNOWN' % code
Close the wrapped response if possible.

Definition at line 687 of file wrappers.py.

00687 
00688     def close(self):
00689         """Close the wrapped response if possible."""
00690         if hasattr(self.response, 'close'):
00691             self.response.close()

Here is the caller graph for this function:

def MoinMoin.support.werkzeug.wrappers.BaseResponse.delete_cookie (   self,
  key,
  path = '/',
  domain = None 
)
Delete a cookie.  Fails silently if key doesn't exist.

:param key: the key (name) of the cookie to be deleted.
:param path: if the cookie that should be deleted was limited to a
     path, the path has to be defined here.
:param domain: if the cookie that should be deleted was limited to a
       domain, that domain has to be defined here.

Definition at line 635 of file wrappers.py.

00635 
00636     def delete_cookie(self, key, path='/', domain=None):
00637         """Delete a cookie.  Fails silently if key doesn't exist.
00638 
00639         :param key: the key (name) of the cookie to be deleted.
00640         :param path: if the cookie that should be deleted was limited to a
00641                      path, the path has to be defined here.
00642         :param domain: if the cookie that should be deleted was limited to a
00643                        domain, that domain has to be defined here.
00644         """
00645         self.set_cookie(key, expires=0, max_age=0, path=path, domain=domain)

Here is the call graph for this function:

This is automatically called right before the response is started
and should fix common mistakes in headers.  For example location
headers are joined with the root URL here.

:param environ: the WSGI environment of the request to be used for
        the applied fixes.

Definition at line 669 of file wrappers.py.

00669 
00670     def fix_headers(self, environ):
00671         """This is automatically called right before the response is started
00672         and should fix common mistakes in headers.  For example location
00673         headers are joined with the root URL here.
00674 
00675         :param environ: the WSGI environment of the request to be used for
00676                         the applied fixes.
00677         """
00678         if 'Location' in self.headers:
00679             self.headers['Location'] = urlparse.urljoin(
00680                 get_current_url(environ, root_only=True),
00681                 self.headers['Location']
00682             )
00683         if 100 <= self.status_code < 200 or self.status_code == 204:
00684             self.headers['Content-Length'] = 0
00685         elif self.status_code == 304:
00686             remove_entity_headers(self.headers)

Here is the call graph for this function:

Here is the caller graph for this function:

def MoinMoin.support.werkzeug.wrappers.BaseResponse.force_type (   cls,
  response,
  environ = None 
)
Enforce that the WSGI response is a response object of the current
type.  Werkzeug will use the :class:`BaseResponse` internally in many
situations like the exceptions.  If you call :meth:`get_response` on an
exception you will get back a regular :class:`BaseResponse` object, even
if you are using a custom subclass.

This method can enforce a given response type, and it will also
convert arbitrary WSGI callables into response objects if an environ
is provided::

    # convert a Werkzeug response object into an instance of the
    # MyResponseClass subclass.
    response = MyResponseClass.force_type(response)

    # convert any WSGI application into a response object
    response = MyResponseClass.force_type(response, environ)

This is especially useful if you want to post-process responses in
the main dispatcher and use functionality provided by your subclass.

Keep in mind that this will modify response objects in place if
possible!

:param response: a response object or wsgi application.
:param environ: a WSGI environment object.
:return: a response object.

Definition at line 518 of file wrappers.py.

00518 
00519     def force_type(cls, response, environ=None):
00520         """Enforce that the WSGI response is a response object of the current
00521         type.  Werkzeug will use the :class:`BaseResponse` internally in many
00522         situations like the exceptions.  If you call :meth:`get_response` on an
00523         exception you will get back a regular :class:`BaseResponse` object, even
00524         if you are using a custom subclass.
00525 
00526         This method can enforce a given response type, and it will also
00527         convert arbitrary WSGI callables into response objects if an environ
00528         is provided::
00529 
00530             # convert a Werkzeug response object into an instance of the
00531             # MyResponseClass subclass.
00532             response = MyResponseClass.force_type(response)
00533 
00534             # convert any WSGI application into a response object
00535             response = MyResponseClass.force_type(response, environ)
00536 
00537         This is especially useful if you want to post-process responses in
00538         the main dispatcher and use functionality provided by your subclass.
00539 
00540         Keep in mind that this will modify response objects in place if
00541         possible!
00542 
00543         :param response: a response object or wsgi application.
00544         :param environ: a WSGI environment object.
00545         :return: a response object.
00546         """
00547         if not isinstance(response, BaseResponse):
00548             if environ is None:
00549                 raise TypeError('cannot convert WSGI application into '
00550                                 'response objects without an environ')
00551             response = BaseResponse(*run_wsgi_app(response, environ))
00552         response.__class__ = cls
00553         return response

Here is the call graph for this function:

Call this method if you want to make your response object ready for
being pickled.  This buffers the generator if there is one.

Definition at line 692 of file wrappers.py.

00692 
00693     def freeze(self):
00694         """Call this method if you want to make your response object ready for
00695         being pickled.  This buffers the generator if there is one.
00696         """
00697         BaseResponse.data.__get__(self)

def MoinMoin.support.werkzeug.wrappers.BaseResponse.from_app (   cls,
  app,
  environ,
  buffered = False 
)
Create a new response object from an application output.  This
works best if you pass it an application that returns a generator all
the time.  Sometimes applications may use the `write()` callable
returned by the `start_response` function.  This tries to resolve such
edge cases automatically.  But if you don't get the expected output
you should set `buffered` to `True` which enforces buffering.

:param app: the WSGI application to execute.
:param environ: the WSGI environment to execute against.
:param buffered: set to `True` to enforce buffering.
:return: a response object.

Definition at line 555 of file wrappers.py.

00555 
00556     def from_app(cls, app, environ, buffered=False):
00557         """Create a new response object from an application output.  This
00558         works best if you pass it an application that returns a generator all
00559         the time.  Sometimes applications may use the `write()` callable
00560         returned by the `start_response` function.  This tries to resolve such
00561         edge cases automatically.  But if you don't get the expected output
00562         you should set `buffered` to `True` which enforces buffering.
00563 
00564         :param app: the WSGI application to execute.
00565         :param environ: the WSGI environment to execute against.
00566         :param buffered: set to `True` to enforce buffering.
00567         :return: a response object.
00568         """
00569         return cls(*run_wsgi_app(app, environ, buffered))

Here is the call graph for this function:

This returns the headers in the target charset as list.  It's used
in __call__ to get the headers for the response.

Definition at line 647 of file wrappers.py.

00647 
00648     def header_list(self):
00649         """This returns the headers in the target charset as list.  It's used
00650         in __call__ to get the headers for the response.
00651         """
00652         return self.headers.to_list(self.charset)

Here is the caller graph for this function:

If the response is streamed (the response is not a sequence) this
property is `True`.  In this case streamed means that there is no
information about the number of iterations.  This is usully `True`
if a generator is passed to the response object.

This is useful for checking before applying some sort of post
filtering that should not take place for streamed responses.

Definition at line 654 of file wrappers.py.

00654 
00655     def is_streamed(self):
00656         """If the response is streamed (the response is not a sequence) this
00657         property is `True`.  In this case streamed means that there is no
00658         information about the number of iterations.  This is usully `True`
00659         if a generator is passed to the response object.
00660 
00661         This is useful for checking before applying some sort of post
00662         filtering that should not take place for streamed responses.
00663         """
00664         try:
00665             len(self.response)
00666         except TypeError:
00667             return False
00668         return True

Iter the response encoded with the encoding specified.  If no
encoding is given the encoding from the class is used.  Note that
this does not encode data that is already a bytestring.  If the
response object is invoked as WSGI application the return value
of this method is used as application iterator except if
:attr:`direct_passthrough` was activated.

Definition at line 597 of file wrappers.py.

00597 
00598     def iter_encoded(self, charset=None):
00599         """Iter the response encoded with the encoding specified.  If no
00600         encoding is given the encoding from the class is used.  Note that
00601         this does not encode data that is already a bytestring.  If the
00602         response object is invoked as WSGI application the return value
00603         of this method is used as application iterator except if
00604         :attr:`direct_passthrough` was activated.
00605         """
00606         charset = charset or self.charset or 'ascii'
00607         for item in self.response:
00608             if isinstance(item, unicode):
00609                 yield item.encode(charset)
00610             else:
00611                 yield str(item)

Here is the call graph for this function:

Here is the caller graph for this function:

def MoinMoin.support.werkzeug.wrappers.BaseResponse.set_cookie (   self,
  key,
  value = '',
  max_age = None,
  expires = None,
  path = '/',
  domain = None,
  secure = None,
  httponly = False 
)
Sets a cookie. The parameters are the same as in the cookie `Morsel`
object in the Python standard library but it accepts unicode data, too.

:param key: the key (name) of the cookie to be set.
:param value: the value of the cookie.
:param max_age: should be a number of seconds, or `None` (default) if
        the cookie should last only as long as the client's
        browser session.
:param expires: should be a `datetime` object or UNIX timestamp.
:param domain: if you want to set a cross-domain cookie.  For example,
       ``domain=".example.com"`` will set a cookie that is
       readable by the domain ``www.example.com``,
       ``foo.example.com`` etc.  Otherwise, a cookie will only
       be readable by the domain that set it.
:param path: limits the cookie to a given path, per default it will
     span the whole domain.

Definition at line 613 of file wrappers.py.

00613 
00614                    path='/', domain=None, secure=None, httponly=False):
00615         """Sets a cookie. The parameters are the same as in the cookie `Morsel`
00616         object in the Python standard library but it accepts unicode data, too.
00617 
00618         :param key: the key (name) of the cookie to be set.
00619         :param value: the value of the cookie.
00620         :param max_age: should be a number of seconds, or `None` (default) if
00621                         the cookie should last only as long as the client's
00622                         browser session.
00623         :param expires: should be a `datetime` object or UNIX timestamp.
00624         :param domain: if you want to set a cross-domain cookie.  For example,
00625                        ``domain=".example.com"`` will set a cookie that is
00626                        readable by the domain ``www.example.com``,
00627                        ``foo.example.com`` etc.  Otherwise, a cookie will only
00628                        be readable by the domain that set it.
00629         :param path: limits the cookie to a given path, per default it will
00630                      span the whole domain.
00631         """
00632         self.headers.add('Set-Cookie', dump_cookie(key, value, max_age,
00633                          expires, path, domain, secure, httponly,
00634                          self.charset))

Here is the call graph for this function:

Here is the caller graph for this function:


Member Data Documentation

Definition at line 483 of file wrappers.py.

Definition at line 485 of file wrappers.py.

Definition at line 484 of file wrappers.py.

Definition at line 515 of file wrappers.py.

Definition at line 496 of file wrappers.py.

Definition at line 490 of file wrappers.py.

Definition at line 514 of file wrappers.py.


Property Documentation

MoinMoin.support.werkzeug.wrappers.BaseResponse.data = property(_get_data, _set_data, doc=_get_data.__doc__) [static]

Definition at line 594 of file wrappers.py.

Initial value:
property(_get_status_code, _set_status_code,
                           'The HTTP Status code as number')

Definition at line 580 of file wrappers.py.


The documentation for this class was generated from the following file: