API docs: fresco.util


Common utilities for writing applications in fresco

fresco.util.common.object_or_404(ob, exception=<class 'fresco.exceptions.NotFound'>)[source]

Return the value of ob if it is not None. Otherwise raise a NotFound exception.


Security-related utilities

fresco.util.security.check_equal_constant_time(a, b)[source]

Return True if string a is equal to string b.

If a and b are of the same length, this function will take the same amount of time to execute, regardless of whether or not a and b are equal.


Utilities for working with data on the HTTP level

fresco.util.http.ALLOWED_ENCODINGS = {'greek', 'ks-c-5601', 'latin8', 'johab', '932', 'iso8859-15', 'ibm864', 'cp037', 'l3', 'cp154', 'iso2022-jp', 'iso8859-8', 'utf-32-le', 'csbig5', '852', 'gb18030-2000', 'ibm1026', 'latin10', 'ks-x-1001', 'cp1256', 'macintosh', 'windows-1256', 'iso-2022-jp-3', 'utf16', 'utf-32', 'l7', 'cp949', 'iso-2022-jp-1', 'latin2', 'iso2022-jp-2004', 'windows-1250', 'csiso2022jp', 'iso-8859-1', 'cp65001', 'sjis', 'uhc', 'utf-16le', 'iso-8859-6', 'big5-tw', 'mac-cyrillic', 'iso-8859-15', 'ibm865', '858', 'ebcdic-cp-ch', 'cp861', 'ibm860', 'u32', '860', 'ksx1001', 'cp932', 'hzgb', 'iso8859-5', 'cp869', 'mac-turkish', '857', 'latin3', 'cyrillic-asian', 'cyrillic', '865', '850', 's-jis', 'thai', '862', 'jisx0213', 'macroman', '646', 'hz', 'ms936', 'big5-hkscs', 'macgreek', 'iso2022-jp-3', '949', 'shiftjis2004', 'l4', 'utf-16-le', 'cp273', 'cp864', 'cp500', '950', 'cp1006', 'iso2022jp', 'csiso2022kr', 'cp1125', 'iso-8859-2', 'iso-8859-3', 'latin6', 'ibm852', 'ukrainian', '437', 'big5hkscs', 'iso8859-6', 'iso2022-jp-1', 'hkscs', 'shift-jis', 'cp1026', 'euc-jisx0213', 'unicode-1-1-utf-7', 'windows-1257', 'gbk', 'utf32', 'ibm037', 'iso-8859-7', 'iso8859-7', 'ms-kanji', 'iso-8859-8', 'cp-is', 'cp852', 'l10', 'ibm869', 'shift-jis-2004', 'maccyrillic', 'l8', '863', 'korean', 'latin5', 'iso-8859-16', 'iso-ir-58', 'ruscii', 'ibm858', 'l2', 'eucjp', 'latin-1', 'iso-2022-jp', 'cp819', 'iso2022-jp-2', 'ibm1125', 'euckr', 'cp862', 'ebcdic-cp-he', 'iso2022jp-2', '861', 'mskanji', 'csptcp154', 'cp-gr', 'utf-16-be', 'eucgb2312-cn', 'windows-1254', 'cp936', 'cp950', 'latin7', 'pt154', 'utf-8', 'cp1252', 'utf-8-sig', 'mac-latin2', 'iso8859-16', 'l9', 'sjis2004', 'iso-8859-14', 'shiftjis', '869', 'euc-cn', 'l6', 'iso8859-3', 'utf-32le', 'iso-8859-10', 'cp866u', '1125', 'russian', 'windows-1253', 'latin9', 'utf-16', 'euc-jis-2004', 'utf-32-be', 'cp850', 'cp874', 'iso2022-jp-ext', 'gb18030', 'iso2022-kr', 'ksc5601', 'l5', 'ibm424', 'cp855', 'sjis-2004', 'windows-1252', 'latin4', 'ibm775', 'cp860', 'cp720', 'mac-roman', 'ibm500', 'euc-kr', 'euc-jp', 'cp437', 'cp858', 'gb2312-1980', 'iso-2022-kr', 'ibm857', 'ibm861', 'hz-gb', 'us-ascii', 'hebrew', 'u16', 'cp1361', 'ms932', 'cp1251', 'ms1361', 'sjisx0213', 'iso2022jp-2004', 'u8', 'ms949', 'cp866', 'iso8859-14', 'cp775', 'cp1253', 'iso-2022-jp-2004', 'chinese', 'latin1', 'u7', 'iso2022kr', 'cp1257', 'cp1250', 'iso8859-4', 'ibm850', 'windows-1251', 'maclatin2', 'cp1140', 'windows-1255', 'iso-8859-13', 'utf8', 'cp875', 'ptcp154', 'cp1255', 'shift-jisx0213', 'cp1254', '273', 'iso-2022-jp-2', 'koi8-u', 'koi8-r', 'shiftjisx0213', 'ebcdic-cp-be', 'utf-32be', 'iso2022jp-ext', 'urdu', 'cp857', 'maciceland', 'ibm437', 'greek8', 'windows-1258', 'ms950', 'mac-greek', 'hz-gb-2312', 'ujis', 'cp737', 'macturkish', 'maccentraleurope', 'csibm273', 'csshiftjis', 'iso8859-10', 'ibm039', 'ibm855', 'utf-7', 'cp863', '936', 'iso-8859-4', 'mac-iceland', 'ascii', 'cp1258', 'eucjis2004', 'cp865', 'iso2022jp-1', 'iso8859-2', 'u-jis', 'iso2022jp-3', 'utf-16be', 'ibm866', 'iso8859-1', 'arabic', 'big5', 'iso-8859-5', '866', 'ibm863', 'euccn', 'ibm1140', 'eucjisx0213', 'iso8859-13', 'cp424', 'iso8859-9', '855', 'l1', 'gb2312-80', 'ibm273', '8859', 'ks-c-5601-1987', 'iso-8859-9', 'utf', 'cp856', 'iso-2022-jp-ext', 's-jisx0213', 'ibm862', 'latin', 'gb2312', 'csiso58gb231280'}

Allowed character encodings. This list is based on the list of standard encodings here:

Python specific encodings and binary transformations (eg zlib decompression) are excluded to avoid zip bomb style attacks.

fresco.util.http.CHUNK_SIZE = 8192

Data chunk size to read from the input stream (wsgi.input)

class fresco.util.http.FileUpload(filename, headers, fileob)[source]

Represent a file uploaded in an HTTP form submission


Save the upload to the file object or path fileob

Parameters:fileob – a file-like object open for writing, or the path to the file to be written
class fresco.util.http.HTTPMessage(policy=Compat32())[source]

Represent HTTP request message headers

exception fresco.util.http.MissingContentLength(*args, **kwargs)[source]

No Content-Length header given

class fresco.util.http.ParsedContentType(content_type, encoding, params)

Alias for field number 0


Alias for field number 1


Alias for field number 2

exception fresco.util.http.TooBig(*args, **kwargs)[source]

Request body is too big

fresco.util.http.encode_multipart(data=None, files=None, charset='UTF-8', **kwargs)[source]

Encode data using multipart/form-data encoding, returning a tuple of (<encoded data>, <environ items>).

  • data – POST data to be encoded, either a dict or list of (name, value) tuples.
  • charset – Encoding used for any unicode values encountered in data
  • files – list of (name, filename, content_type, data) tuples. data may be either a byte string, iterator or file-like object.
  • kwargs – other data items as keyword arguments

a tuple of (<encoded_data>, <environ_items>), where encoded_data is a BytesIO object and environ is a dict containing the Content-Type and Content-Length headers encoded for inclusion in a WSGI environ dict.

fresco.util.http.get_body_bytes(environ, max_size=16384)[source]

Read a single message body from environ[‘wsgi.input’], returning a bytes object.

fresco.util.http.get_content_type_info(environ, default_type='application/octet-stream', default_encoding='iso-8859-1')[source]

Read and parse the Content-Type header and return a ParsedContentType object.

fresco.util.http.parse_body(environ, fp, default_charset=None, max_size=16384)[source]
Parse the message
(payload as a byte string, content-type, encoding)
fresco.util.http.parse_header(header, ie_workaround=False, _broken_encoding_sniffer=<built-in method search of _sre.SRE_Pattern object>)[source]

Given a header, return a tuple of (value, [(parameter_name, parameter_value)]).

Example usage:

>>> parse_header("text/html; charset=UTF-8")
('text/html', {'charset': 'UTF-8'})
>>> parse_header("multipart/form-data; boundary=-------7d91772e200be")
('multipart/form-data', {'boundary': '-------7d91772e200be'})
fresco.util.http.parse_multipart(fp, boundary, default_charset, max_size, ie_workaround=True)[source]

Parse data encoded as multipart/form-data. Generate tuples of:

(<field-name>, <data>)

Where data will be a string in the case of a regular input field, or a FileUpload instance if a file was uploaded.

  • fp – input stream from which to read data
  • boundary – multipart boundary string, as specified by the Content-Disposition header
  • default_charset – character set to use for encoding, if not specified by a content-type header. In practice web browsers don’t supply a content-type header so this needs to contain a sensible value.
  • max_size – Maximum size in bytes for any non file upload part
  • ie_workaround – If True (the default), enable a work around for IE’s broken content-disposition header encoding.
fresco.util.http.parse_parameters(s, preserve_backslashes=False)[source]

Return s parsed as a sequence of semi-colon delimited name=value pairs.

Example usage:

>>> from fresco.util.http import parse_parameters
>>> parse_parameters('foo=bar')
{'foo': 'bar'}
>>> parse_parameters('foo="bar\""')
{'foo': 'bar"'}

The preserve_backslashes flag is used to preserve IE compatibility for file upload paths, which it incorrectly encodes without escaping backslashes, eg:

Content-Disposition: form-data; name="file"; filename="C:       mp\Ext.js"

(To be RFC compliant, the backslashes should be doubled up).

fresco.util.http.parse_post(environ, fp, default_charset=None, max_size=16384, max_multipart_size=2097152, ie_workaround=True)[source]

Parse the contents of an HTTP POST request, which may be either application/x-www-form-urlencoded or multipart/form-data encoded.

Returned items are either tuples of (name, value) for simple string values or (name, FileUpload) for uploaded files.

  • max_multipart_size – Maximum size of total data for a multipart form submission
  • max_size – The maximum size of data allowed to be read into memory. For a application/x-www-form-urlencoded submission, this is the maximum size of the entire data. For a multipart/form-data submission, this is the maximum size of any individual field (except file uploads).
fresco.util.http.parse_querystring(data, charset=None, strict=False, keep_blank_values=True, pairsplitter=<built-in method split of _sre.SRE_Pattern object>)[source]

Return (key, value) pairs from the given querystring:

>>> list(parse_querystring('green%20eggs=ham;me=sam+i+am'))
[(u'green eggs', u'ham'), (u'me', u'sam i am')]
  • data – The query string to parse.
  • charset – Character encoding used to decode values. If not specified, fresco.DEFAULT_CHARSET will be used.
  • keep_blank_values – if True, keys without associated values will be returned as empty strings. if False, no key, value pair will be returned.
  • strict – if True, a ValueError will be raised on parsing errors.

Return s parsed as a RFC2045 value, ie:

value := token / quoted-string

Example usage:

>>> from fresco.util.http import parse_value
>>> parse_value('foo')
>>> dequote('"foo"')


Utilities for wrapping IO streams. These are used internally by fresco when parsing wsgi request input streams.

class fresco.util.io.DelimitedInput(raw, delimiter, consume_delimiter=True)[source]

Wrap a PutbackInput to read as far as a delimiter (after which subsequent reads will return empty strings, as if EOF was reached)


>>> from io import BytesIO
>>> s = BytesIO(b'one--two--three')
>>> p = PutbackInput(s)
>>> DelimitedInput(p, b'--').read()
>>> DelimitedInput(p, b'--').read()
>>> DelimitedInput(p, b'--').read()
>>> DelimitedInput(p, b'--').read()

Don’t close the underlying stream unless it has been fully consumed


Return up to size bytes of data from the stream until EOF or delimiter is reached.


Read a single line of up to size bytes from the input stream, or up to delimiter if this is encountered before a complete line is read.

class fresco.util.io.ExpandableOutput(bufsize=16384)[source]

Write-only output object.

Will store data in a BytesIO, until more than bufsize bytes are written, at which point it will switch to storing data in a real file object.


Return the underlying stream (either a BytesIO or file object)


Switch the storage backend to an instance of TemporaryFile.


write, optimized for the TemporaryFile backend


write, optimized for the BytesIO backend.

class fresco.util.io.PutbackInput(raw)[source]

Wrap a file-like object to allow data read to be returned to the buffer.

Only supports serial read-access, ie no seek or write methods.


>>> from io import BytesIO
>>> s = BytesIO(b"the rain in spain\nfalls mainly\non the plain\n")
>>> p = PutbackInput(s)
>>> line = p.readline()
>>> line
'the rain in spain\n'
>>> p.putback(line)
>>> p.readline()
'the rain in spain\n'

Peek ahead size bytes from the stream without consuming any data


Put data back into the stream


Read and return up to size bytes.


Read a single line of up to size bytes.

class fresco.util.io.ReadlinesMixin[source]

Mixin that defines readlines and the iterator interface in terms of underlying readline method.

class fresco.util.io.SizeLimitedInput(raw, length)[source]

Wrap an IO object to prevent reading beyond length bytes.


>>> from io import BytesIO
>>> s = BytesIO(b"the rain in spain\nfalls mainly\non the plain\n")
>>> s = SizeLimitedInput(s, 24)
>>> len(s.read())
>>> s.seek(0)
>>> s.read()
'the rain in spain\nfalls '
>>> s.seek(0)
>>> s.readline()
'the rain in spain\n'
>>> s.readline()
'falls '

Return the minimum of requested and the number of bytes available in the stream. If requested is negative, return the number of bytes available in the stream.


Return up to size bytes from the input stream.


Read a single line of up to size bytes from the input stream.

seek(pos, whence=0)[source]

Seek to position pos. This is a wrapper for the underlying IO’s seek method.


Return the position of the file pointer in the stream.


Utilities for interfacing with WSGI

fresco.util.wsgi.environ_to_unicode(s, enc='UTF-8')[source]

Decode a WSGI environ value to a unicode string

fresco.util.wsgi.unicode_to_environ(s, enc='UTF-8')[source]

Return a unicode string encoded for a WSGI environ value

In python 2 this function returns s encoded using the specified encoding

In python 3 this returns a ‘bytes-as-unicode’ string:

  • encode s using the specified encoding (eg utf8)
  • decode the resulting byte string as latin-1

Decode a WSGI environ value to a bytes object


Encode a byte string to a WSGI environ value

For Python 2, this simply returns s. For Python 3 this returns a ‘bytes-as-unicode’ string.

class fresco.util.wsgi.StartResponseWrapper(start_response)[source]

Wrapper class for the start_response callable, allowing middleware applications to intercept and interrogate the proxied start_response arguments.


>>> def my_wsgi_app(environ, start_response):
...     start_response('200 OK', [('Content-Type', 'text/plain')])
...     return ['Whoa nelly!']
>>> def my_other_wsgi_app(environ, start_response):
...     responder = StartResponseWrapper(start_response)
...     result = my_wsgi_app(environ, responder)
...     print "Got status", responder.status
...     print "Got headers", responder.headers
...     responder.call_start_response()
...     return result
>>> from flea import Agent
>>> result = Agent(my_other_wsgi_app).get('/')
Got status 200 OK
Got headers [('Content-Type', 'text/plain')]

See also Response.from_wsgi, which takes a wsgi callable, environ and start_response, and returns a Response object, allowing the client to further interrogate and customize the WSGI response.

Note that it is usually not advised to use this directly in middleware as start_response may not be called directly from the WSGI application, but rather from the iterator it returns. In this case the middleware may need logic to accommodate this. It is usually safer to use Response.from_wsgi, which takes this into account.


Invoke the wrapped WSGI start_response function.

class fresco.util.wsgi.ClosingIterator(iterable, *close_funcs)[source]

Wrap a WSGI iterator to allow additional close functions to be called on application exit.


>>> class filelikeobject(object):
...     def read(self):
...         print "file read!"
...         return ''
...     def close(self):
...         print "file closed!"
>>> def app(environ, start_response):
...     f = filelikeobject()
...     start_response('200 OK', [('Content-Type', 'text/plain')])
...     return ClosingIterator(iter(f.read, ''), f.close)
>>> from flea import Agent
>>> m = Agent(app).get('/')
file read!
file closed!

Call all close functions listed in *close_funcs.


Return the next item from iterator

fresco.util.wsgi.make_environ(url='/', environ=None, wsgi_input=b'', middleware=True, **kwargs)[source]

Return a WSGI environ dict populated with values modelling the specified request url and data.

  • url – The URL for the request, eg /index.html or /search?q=foo. Note that url must be properly URL encoded.
  • environ – values to pass into the WSGI environ dict
  • wsgi_input – The input stream to use in the wsgi.input key of the environ dict
  • middleware – If False the middleware stack will not be invoked. Disabling the middleware can speed up the execution considerably, but it will no longer give an accurate simulation of a real HTTP request.
  • kwargs – additional keyword arguments will be passed into the WSGI request environment