OpenQuizz
Une application de gestion des contenus pédagogiques
BaseResponse Class Reference
Inheritance diagram for BaseResponse:
Collaboration diagram for BaseResponse:

Public Member Functions

def __init__ (self, response=None, status=None, headers=None, mimetype=None, content_type=None, direct_passthrough=False)
 
def call_on_close (self, func)
 
def __repr__ (self)
 
def force_type (cls, response, environ=None)
 
def from_app (cls, app, environ, buffered=False)
 
def status_code (self)
 
def status_code (self, code)
 
def status (self)
 
def status (self, value)
 
def get_data (self, as_text=False)
 
def set_data (self, value)
 
def calculate_content_length (self)
 
def make_sequence (self)
 
def iter_encoded (self)
 
def set_cookie (self, key, value="", max_age=None, expires=None, path="/", domain=None, secure=False, httponly=False, samesite=None)
 
def delete_cookie (self, key, path="/", domain=None)
 
def is_streamed (self)
 
def is_sequence (self)
 
def close (self)
 
def __enter__ (self)
 
def __exit__ (self, exc_type, exc_value, tb)
 
def freeze (self)
 
def get_wsgi_headers (self, environ)
 
def get_app_iter (self, environ)
 
def get_wsgi_response (self, environ)
 
def __call__ (self, environ, start_response)
 

Data Fields

 headers
 
 status_code
 
 status
 
 direct_passthrough
 
 response
 

Static Public Attributes

 charset
 
 default_status
 
 default_mimetype
 
 implicit_sequence_conversion
 
 autocorrect_location_header
 
 automatically_set_content_length
 
 max_cookie_size
 

Properties

 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.wrappers 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
known interface.

Per default the response object will assume all the text data is `utf-8`
encoded.  Please refer to :doc:`the unicode chapter </unicode>` 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:`~werkzeug.datastructures.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/`, the charset parameter of the response
object is appended to it.  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 a
                :class:`~werkzeug.datastructures.Headers` object.
:param mimetype: the mimetype for the response.  See notice above.
:param content_type: the content type for the response.  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 through
                           unchanged (see :func:`wrap_file` for more
                           details.)

Constructor & Destructor Documentation

◆ __init__()

def __init__ (   self,
  response = None,
  status = None,
  headers = None,
  mimetype = None,
  content_type = None,
  direct_passthrough = False 
)

Member Function Documentation

◆ __call__()

def __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.
:return: an application iterator

◆ __enter__()

def __enter__ (   self)

◆ __exit__()

def __exit__ (   self,
  exc_type,
  exc_value,
  tb 
)

◆ __repr__()

def __repr__ (   self)

◆ calculate_content_length()

def calculate_content_length (   self)
Returns the content length if available or `None` otherwise.

◆ call_on_close()

def call_on_close (   self,
  func 
)
Adds a function to the internal list of functions that should
be called as part of closing down the response.  Since 0.7 this
function also returns the function that was passed so that this
can be used as a decorator.

.. versionadded:: 0.6

◆ close()

def close (   self)
Close the wrapped response if possible.  You can also use the object
in a with statement which will automatically close it.

.. versionadded:: 0.9
   Can now be used in a with statement.

◆ delete_cookie()

def 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.

◆ force_type()

def 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.

◆ freeze()

def freeze (   self)
Call this method if you want to make your response object ready for
being pickled.  This buffers the generator if there is one.  It will
also set the `Content-Length` header to the length of the body.

.. versionchanged:: 0.6
   The `Content-Length` header is now set.

◆ from_app()

def 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.

◆ get_app_iter()

def get_app_iter (   self,
  environ 
)
Returns the application iterator for the given environ.  Depending
on the request method and the current status code the return value
might be an empty response rather than the one from the response.

If the request method is `HEAD` or the status code is in a range
where the HTTP specification requires an empty response, an empty
iterable is returned.

.. versionadded:: 0.6

:param environ: the WSGI environment of the request.
:return: a response iterable.

◆ get_data()

def get_data (   self,
  as_text = False 
)
The string representation of the request body.  Whenever you call
this property the request iterable is encoded and flattened.  This
can lead to unwanted behavior if you stream big data.

This behavior can be disabled by setting
:attr:`implicit_sequence_conversion` to `False`.

If `as_text` is set to `True` the return value will be a decoded
unicode string.

.. versionadded:: 0.9

◆ get_wsgi_headers()

def get_wsgi_headers (   self,
  environ 
)
This is automatically called right before the response is started
and returns headers modified for the given environment.  It returns a
copy of the headers from the response with some modifications applied
if necessary.

For example the location header (if present) is joined with the root
URL of the environment.  Also the content length is automatically set
to zero here for certain status codes.

.. versionchanged:: 0.6
   Previously that function was called `fix_headers` and modified
   the response object in place.  Also since 0.6, IRIs in location
   and content-location headers are handled properly.

   Also starting with 0.6, Werkzeug will attempt to set the content
   length if it is able to figure it out on its own.  This is the
   case if all the strings in the response iterable are already
   encoded and the iterable is buffered.

:param environ: the WSGI environment of the request.
:return: returns a new :class:`~werkzeug.datastructures.Headers`
 object.

◆ get_wsgi_response()

def get_wsgi_response (   self,
  environ 
)
Returns the final WSGI response as tuple.  The first item in
the tuple is the application iterator, the second the status and
the third the list of headers.  The response returned is created
specially for the given environment.  For example if the request
method in the WSGI environment is ``'HEAD'`` the response will
be empty and only the headers and status code will be present.

.. versionadded:: 0.6

:param environ: the WSGI environment of the request.
:return: an ``(app_iter, status, headers)`` tuple.

◆ is_sequence()

def is_sequence (   self)
If the iterator is buffered, this property will be `True`.  A
response object will consider an iterator to be buffered if the
response attribute is a list or tuple.

.. versionadded:: 0.6

◆ is_streamed()

def is_streamed (   self)
If the response is streamed (the response is not an iterable with
a length information) this property is `True`.  In this case streamed
means that there is no information about the number of iterations.
This is usually `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.

◆ iter_encoded()

def iter_encoded (   self)
Iter the response encoded with the encoding of the response.
If the response object is invoked as WSGI application the return
value of this method is used as application iterator unless
:attr:`direct_passthrough` was activated.

◆ make_sequence()

def make_sequence (   self)
Converts the response iterator in a list.  By default this happens
automatically if required.  If `implicit_sequence_conversion` is
disabled, this method is not automatically called and some properties
might raise exceptions.  This also encodes all the items.

.. versionadded:: 0.6

◆ set_cookie()

def set_cookie (   self,
  key,
  value = "",
  max_age = None,
  expires = None,
  path = "/",
  domain = None,
  secure = False,
  httponly = False,
  samesite = None 
)
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.

A warning is raised if the size of the cookie header exceeds
:attr:`max_cookie_size`, but the header will still be set.

: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 path: limits the cookie to a given path, per default it will
     span the whole domain.
: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 secure: If `True`, the cookie will only be available via HTTPS
:param httponly: disallow JavaScript to access the cookie.  This is an
         extension to the cookie standard and probably not
         supported by all browsers.
:param samesite: Limits the scope of the cookie such that it will only
         be attached to requests if those requests are
         "same-site".

◆ set_data()

def set_data (   self,
  value 
)
Sets a new string as response.  The value set must be either a
unicode or bytestring.  If a unicode string is set it's encoded
automatically to the charset of the response (utf-8 by default).

.. versionadded:: 0.9

◆ status() [1/2]

def status (   self)
The HTTP status code as a string.

◆ status() [2/2]

def status (   self,
  value 
)

◆ status_code() [1/2]

def status_code (   self)
The HTTP status code as a number.

◆ status_code() [2/2]

def status_code (   self,
  code 
)

Field Documentation

◆ autocorrect_location_header

autocorrect_location_header
static

◆ automatically_set_content_length

automatically_set_content_length
static

◆ charset

charset
static

◆ default_mimetype

default_mimetype
static

◆ default_status

default_status
static

◆ direct_passthrough

direct_passthrough

◆ headers

headers

◆ implicit_sequence_conversion

implicit_sequence_conversion
static

◆ max_cookie_size

max_cookie_size
static

◆ response

response

◆ status

status

◆ status_code

status_code

Property Documentation

◆ data

data
static
Initial value:
= property(
get_data,
set_data,
doc="A descriptor that calls :meth:`get_data` and :meth:`set_data`.",
)

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