An HTTP response, created by calling an intessa.api.API.
The following attributes all need to be set when constructing a response.
The intessa.api.API instance which created this Response.
An integer representing the HTTP status code of the response.
A case-insensitive dictionary (or dict-like object) containing header names and values.
A bytestring (i.e. str instance) containing the body of the response.
You may optionally set the following:
An instance of intessa.conneg.codec_base.CodecRegister, to be used for decoding this response. Defaults to DEFAULT_REGISTER.
All the other attributes are dynamically created by the class itself.
A intessa.conneg.ContentType for this response.
Use this to implement conditional handling of various types.
Raises : | AttributeError if no Content-Type header was given. |
---|
Example:
>>> resp = Response(None, 200,
... {'content-type': 'text/html; charset=utf-8'},
... '<html></html>')
>>> resp.type
ContentType('text/html; charset=utf-8')
>>> resp.type.media_type
'text/html'
>>> resp.type.params['charset']
'utf-8'
The content of this HTTP response, decoded into a Python object.
This method uses the codec_register to decode responses. An object is retrieved simply by passing the content type and content bytestring into codec_register.decode().
Note that the object will be decoded once per access; store a reference to the returned object if you wish to use it more than once.
>>> json = Response(None, 200,
... {'content-type': 'application/json'},
... '{"a": 1}')
>>> json.value
{'a': 1}
>>> text = Response(None, 200,
... {'content-type': 'text/plain; charset=utf-8'},
... 'H\xc3\xa9llo W\xc3\xb6rld')
>>> text.value
u'H\xe9llo W\xf6rld'
Raiseable responses (for non-successful HTTP responses).
On the one hand, these exceptions can be used in exactly the same way as Response:
>>> response = Response(api=None, status_code=403,
... headers={'content-type': 'application/json'},
... content='{"error": "Forbidden"}')
>>> exc = ResponseException(response)
>>> exc
<intessa.Error[403, application/json]>
>>> exc.value
{'error': 'Forbidden'}
However, the main use of response exceptions is for raising and subsequent pattern matching using except statements:
>>> try:
... raise exc
... except ResponseException['4xx'], captured:
... print "Captured!"
Captured!
In this case, for example, you can capture 4xx, 40x and 403; the class hierarchy will be dynamically created and cached on ResponseException itself:
>>> isinstance(exc, ResponseException['4xx'])
True
>>> isinstance(exc, ResponseException['40x'])
True
>>> isinstance(exc, ResponseException['403'])
True
The class is aliased as intessa.Error for the sake of convenience:
>>> import intessa
>>> intessa.Error['403'] is intessa.ResponseException['403']
True
list of weak references to the object (if defined)