WSGI Helpers — Werkzeug v0.8.2 documentation

### Navigation

- index
- modules |
- next |
- previous |
- Werkzeug v0.8.2 documentation »

# WSGI Helpers

The following classes and functions are designed to make working with the WSGI specification easier or operate on the WSGI layer. All the functionality from this module is available on the high-level Request/Response classes.

## Iterator / Stream Helpers

These classes and functions simplify working with the WSGI application iterator and the input stream.

class `werkzeug.wsgi.` `ClosingIterator`(iterable, callbacks=None)

  The WSGI specification requires that all middlewares and gateways respect the close callback of an iterator. Because it is useful to add another close action to a returned iterator and adding a custom iterator is a boring task this class can be used for that:

      return ClosingIterator(app(environ, start_response), [cleanup_session,
                                                            cleanup_locals])

  If there is just one close function it can be passed instead of the list.

  A closing iterator is not needed if the application uses response objects and finishes the processing if the response is started:

      try:
          return response(environ, start_response)
      finally:
          cleanup_session()
          cleanup_locals()

class `werkzeug.wsgi.` `FileWrapper`(file, buffer_size=8192)

  This class can be used to convert a `file`-like object into an iterable. It yields buffer_size blocks until the file is fully read.

  You should not use this class directly but rather use the `wrap_file()` function that uses the WSGI server’s file wrapper support if it’s available.

  New in version 0.5.

  If you’re using this object together with a `BaseResponse` you have to use the direct_passthrough mode.

  Parameters: | file – a `file`-like object with a `read()` method. buffer_size – number of bytes for one iteration.

class `werkzeug.wsgi.` `LimitedStream`(stream, limit, silent=True)

  Wraps a stream so that it doesn’t read more than n bytes. If the stream is exhausted and the caller tries to get more bytes from it `on_exhausted()` is called which by default returns an empty string. The return value of that function is forwarded to the reader function. So if it returns an empty string `read()` will return an empty string as well.

  The limit however must never be higher than what the stream can output. Otherwise `readlines()` will try to read past the limit.

  The silent parameter has no effect if `is_exhausted()` is overriden by a subclass.

  Changed in version 0.6: Non-silent usage was deprecated because it causes confusion. If you want that, override `is_exhausted()` and raise a `BadRequest` yourself.

  Note on WSGI compliance

  calls to `readline()` and `readlines()` are not WSGI compliant because it passes a size argument to the readline methods. Unfortunately the WSGI PEP is not safely implementable without a size argument to `readline()` because there is no EOF marker in the stream. As a result of that the use of `readline()` is discouraged.

  For the same reason iterating over the `LimitedStream` is not portable. It internally calls `readline()`.

  We strongly suggest using `read()` only or using the `make_line_iter()` which safely iterates line-based over a WSGI input stream.

  Parameters: | stream – the stream to wrap. limit – the limit for the stream, must not be longer than what the string can provide if the stream does not end with EOF (like wsgi.input) silent – If set to True the stream will allow reading past the limit and will return an empty string.

  `exhaust`(chunk_size=16384)

    Exhaust the stream. This consumes all the data left until the limit is reached.

    Parameters: | chunk_size – the size for a chunk. It will read the chunk until the stream is exhausted and throw away the results.

  `is_exhausted`

    If the stream is exhausted this attribute is True.

  `on_disconnect`()

    What should happen if a disconnect is detected? The return value of this function is returned from read functions in case the client went away. By default a `ClientDisconnected` exception is raised.

  `on_exhausted`()

    This is called when the stream tries to read past the limit. The return value of this function is returned from the reading function.

  `read`(size=None)

    Read size bytes or if size is not provided everything is read.

    Parameters: | size – the number of bytes read.

  `readline`(size=None)

    Reads one line from the stream.

  `readlines`(size=None)

    Reads a file into a list of strings. It calls `readline()` until the file is read to the end. It does support the optional size argument if the underlaying stream supports it for readline.

`werkzeug.wsgi.` `make_line_iter`(stream, limit=None, buffer_size=10240)

  Safely iterates line-based over an input stream. If the input stream is not a `LimitedStream` the limit parameter is mandatory.

  This uses the stream’s `read()` method internally as opposite to the `readline()` method that is unsafe and can only be used in violation of the WSGI specification. The same problem applies to the __iter__ function of the input stream which calls `readline()` without arguments.

  If you need line-by-line processing it’s strongly recommended to iterate over the input stream using this helper function.

  Changed in version 0.8: This function now ensures that the limit was reached.

  Parameters: | stream – the stream to iterate over. limit – the limit in bytes for the stream. (Usually content length. Not necessary if the stream is a `LimitedStream`. buffer_size – The optional buffer size.

`werkzeug.wsgi.` `make_chunk_iter`(stream, separator, limit=None, buffer_size=10240)

  Works like `make_line_iter()` but accepts a separator which divides chunks. If you want newline based processing you shuold use `make_limited_stream()` instead as it supports arbitrary newline markers.

  New in version 0.8.

  Parameters: | stream – the stream to iterate over. separator – the separator that divides chunks. limit – the limit in bytes for the stream. (Usually content length. Not necessary if the stream is a `LimitedStream`. buffer_size – The optional buffer size.

`werkzeug.wsgi.` `wrap_file`(environ, file, buffer_size=8192)

  Wraps a file. This uses the WSGI server’s file wrapper if available or otherwise the generic `FileWrapper`.

  New in version 0.5.

  If the file wrapper from the WSGI server is used it’s important to not iterate over it from inside the application but to pass it through unchanged. If you want to pass out a file wrapper inside a response object you have to set `direct_passthrough` to True.

  More information about file wrappers are available in PEP 333.

  Parameters: | file – a `file`-like object with a `read()` method. buffer_size – number of bytes for one iteration.

## Environ Helpers

These functions operate on the WSGI environment. They extract useful information or perform common manipulations:

`werkzeug.wsgi.` `get_host`(environ)

  Return the real host for the given WSGI environment. This takes care of the X-Forwarded-Host header.

  Parameters: | environ – the WSGI environment to get the host of.

`werkzeug.wsgi.` `get_current_url`(environ, root_only=False, strip_querystring=False, host_only=False)

  A handy helper function that recreates the full URL for the current request or parts of it. Here an example:

      >>> from werkzeug.test import create_environ
      >>> env = create_environ("/?param=foo", "http://localhost/script")
      >>> get_current_url(env)
      'http://localhost/script/?param=foo'
      >>> get_current_url(env, root_only=True)
      'http://localhost/script/'
      >>> get_current_url(env, host_only=True)
      'http://localhost/'
      >>> get_current_url(env, strip_querystring=True)
      'http://localhost/script/'

  Parameters: | environ – the WSGI environment to get the current URL from. root_only – set True if you only want the root URL. strip_querystring – set to True if you don’t want the querystring. host_only – set to True if the host URL should be returned.

`werkzeug.wsgi.` `pop_path_info`(environ)

  Removes and returns the next segment of PATH_INFO, pushing it onto SCRIPT_NAME. Returns None if there is nothing left on PATH_INFO.

  If there are empty segments (`'/foo//bar`) these are ignored but properly pushed to the SCRIPT_NAME:

      >>> env = {'SCRIPT_NAME': '/foo', 'PATH_INFO': '/a/b'}
      >>> pop_path_info(env)
      'a'
      >>> env['SCRIPT_NAME']
      '/foo/a'
      >>> pop_path_info(env)
      'b'
      >>> env['SCRIPT_NAME']
      '/foo/a/b'

  New in version 0.5.

  Parameters: | environ – the WSGI environment that is modified.

`werkzeug.wsgi.` `peek_path_info`(environ)

  Returns the next segment on the PATH_INFO or None if there is none. Works like `pop_path_info()` without modifying the environment:

      >>> env = {'SCRIPT_NAME': '/foo', 'PATH_INFO': '/a/b'}
      >>> peek_path_info(env)
      'a'
      >>> peek_path_info(env)
      'a'

  New in version 0.5.

  Parameters: | environ – the WSGI environment that is checked.

`werkzeug.wsgi.` `extract_path_info`(environ_or_baseurl, path_or_url, charset='utf-8', errors='replace', collapse_http_schemes=True)

  Extracts the path info from the given URL (or WSGI environment) and path. The path info returned is a unicode string, not a bytestring suitable for a WSGI environment. The URLs might also be IRIs.

  If the path info could not be determined, None is returned.

  Some examples:

      >>> extract_path_info('http://example.com/app', '/app/hello')
      u'/hello'
      >>> extract_path_info('http://example.com/app',
      ...                   'https://example.com/app/hello')
      u'/hello'
      >>> extract_path_info('http://example.com/app',
      ...                   'https://example.com/app/hello',
      ...                   collapse_http_schemes=False) is None
      True

  Instead of providing a base URL you can also pass a WSGI environment.

  New in version 0.6.

  Parameters: | environ_or_baseurl – a WSGI environment dict, a base URL or base IRI. This is the root of the application. path_or_url – an absolute path from the server root, a relative path (in which case it’s the path info) or a full URL. Also accepts IRIs and unicode parameters. charset – the charset for byte data in URLs errors – the error handling on decode collapse_http_schemes – if set to False the algorithm does not assume that http and https on the same server point to the same resource.

## Convenience Helpers

`werkzeug.wsgi.` `responder`(f)

  Marks a function as responder. Decorate a function with it and it will automatically call the return value as WSGI application.

  Example:

      @responder
      def application(environ, start_response):
          return Response('Hello World!')

`werkzeug.testapp.` `test_app`(environ, start_response)

  Simple test application that dumps the environment. You can use it to check if Werkzeug is working properly:

      >>> from werkzeug.serving import run_simple
      >>> from werkzeug.testapp import test_app
      >>> run_simple('localhost', 3000, test_app)
       * Running on http://localhost:3000/

  The application displays important information from the WSGI environment, the Python interpreter and the installed libraries.