some docs for Request/Response/mixins

This commit is contained in:
Sébastien Piquemal 2012-02-07 16:22:14 +02:00
parent 21292d31e7
commit 6963fd3623
5 changed files with 31 additions and 44 deletions

View File

@ -37,7 +37,7 @@ __all__ = (
class RequestMixin(object): class RequestMixin(object):
""" """
`Mixin` class to enhance API of Django's standard `request`. `Mixin` class enabling the use of :class:`request.Request` in your views.
""" """
parser_classes = () parser_classes = ()
@ -63,8 +63,8 @@ class RequestMixin(object):
def prepare_request(self, request): def prepare_request(self, request):
""" """
Prepares the request for the request cycle. Returns a custom request instance, Prepares the request cycle. Returns an instance of :class:`request.Request`,
with data and attributes copied from the original request. wrapping the original request object.
""" """
parsers = self.get_parsers() parsers = self.get_parsers()
request = self.request_class(request, parsers=parsers) request = self.request_class(request, parsers=parsers)
@ -74,7 +74,7 @@ class RequestMixin(object):
@property @property
def _parsed_media_types(self): def _parsed_media_types(self):
""" """
Return a list of all the media types that this view can parse. Returns a list of all the media types that this view can parse.
""" """
return [p.media_type for p in self.parser_classes] return [p.media_type for p in self.parser_classes]
@ -83,11 +83,7 @@ class RequestMixin(object):
class ResponseMixin(object): class ResponseMixin(object):
""" """
Adds behavior for pluggable `renderers` to a :class:`views.View` class. `Mixin` class enabling the use of :class:`response.Response` in your views.
Default behavior is to use standard HTTP Accept header content negotiation.
Also supports overriding the content type by specifying an ``_accept=`` parameter in the URL.
Ignores Accept headers from Internet Explorer user agents and uses a sensible browser Accept header instead.
""" """
renderer_classes = () renderer_classes = ()
@ -108,7 +104,7 @@ class ResponseMixin(object):
def prepare_response(self, response): def prepare_response(self, response):
""" """
Prepares the response for the response cycle, and returns the prepared response. Prepares and returns `response`.
This has no effect if the response is not an instance of :class:`response.Response`. This has no effect if the response is not an instance of :class:`response.Response`.
""" """
if hasattr(response, 'request') and response.request is None: if hasattr(response, 'request') and response.request is None:

View File

@ -1,8 +1,8 @@
""" """
The :mod:`request` module provides a :class:`Request` class that can be used The :mod:`request` module provides a :class:`Request` class used to wrap the standard `request`
to wrap the standard `request` object received in all the views, and upgrade its API. object received in all the views.
The wrapped request then offer the following : The wrapped request then offers a richer API, in particular :
- content automatically parsed according to `Content-Type` header, and available as :meth:`.DATA<Request.DATA>` - content automatically parsed according to `Content-Type` header, and available as :meth:`.DATA<Request.DATA>`
- full support of PUT method, including support for file uploads - full support of PUT method, including support for file uploads
@ -24,7 +24,11 @@ __all__ = ('Request',)
class Request(object): class Request(object):
""" """
A wrapper allowing to enhance Django's standard HttpRequest. Wrapper allowing to enhance a standard `HttpRequest` instance.
Kwargs:
- request(HttpRequest). The original request instance.
- parsers(list/tuple). The parsers to use for parsing the request content.
""" """
_USE_FORM_OVERLOADING = True _USE_FORM_OVERLOADING = True
@ -33,10 +37,6 @@ class Request(object):
_CONTENT_PARAM = '_content' _CONTENT_PARAM = '_content'
def __init__(self, request=None, parsers=None): def __init__(self, request=None, parsers=None):
"""
`parsers` is a list/tuple of parser instances and represents the set of psrsers
that the response can handle.
"""
self.request = request self.request = request
if parsers is not None: if parsers is not None:
self.parsers = parsers self.parsers = parsers
@ -185,9 +185,6 @@ class Request(object):
return self.parsers[0] return self.parsers[0]
def _get_parsers(self): def _get_parsers(self):
"""
This just provides a default when parsers havent' been set.
"""
if hasattr(self, '_parsers'): if hasattr(self, '_parsers'):
return self._parsers return self._parsers
return () return ()

View File

@ -2,12 +2,13 @@
The :mod:`response` module provides :class:`Response` and :class:`ImmediateResponse` classes. The :mod:`response` module provides :class:`Response` and :class:`ImmediateResponse` classes.
`Response` is a subclass of `HttpResponse`, and can be similarly instantiated and returned `Response` is a subclass of `HttpResponse`, and can be similarly instantiated and returned
from any view. It is a bit smarter than Django's `HttpResponse` though, for it knows how from any view. It is a bit smarter than Django's `HttpResponse`, for it renders automatically
to use :mod:`renderers` to automatically render its content to a serial format. its content to a serial format by using a list of :mod:`renderers`.
This is achieved by :
- determining the accepted types by checking for an overload or an `Accept` header in the request To determine the content type to which it must render, default behaviour is to use standard
- looking for a suitable renderer and using it on the content given at instantiation HTTP Accept header content negotiation. But `Response` also supports overriding the content type
by specifying an ``_accept=`` parameter in the URL. Also, `Response` will ignore `Accept` headers
from Internet Explorer user agents and use a sensible browser `Accept` header instead.
`ImmediateResponse` is an exception that inherits from `Response`. It can be used `ImmediateResponse` is an exception that inherits from `Response`. It can be used
@ -29,19 +30,17 @@ __all__ = ('Response', 'ImmediateResponse')
class Response(SimpleTemplateResponse): class Response(SimpleTemplateResponse):
""" """
An HttpResponse that may include content that hasn't yet been serialized. An HttpResponse that may include content that hasn't yet been serialized.
Kwargs:
- content(object). The raw content, not yet serialized. This must be simple Python \
data that renderers can handle (e.g.: `dict`, `str`, ...)
- renderers(list/tuple). The renderers to use for rendering the response content.
""" """
_ACCEPT_QUERY_PARAM = '_accept' # Allow override of Accept header in URL query params _ACCEPT_QUERY_PARAM = '_accept' # Allow override of Accept header in URL query params
_IGNORE_IE_ACCEPT_HEADER = True _IGNORE_IE_ACCEPT_HEADER = True
def __init__(self, content=None, status=None, request=None, renderers=None): def __init__(self, content=None, status=None, request=None, renderers=None):
"""
`content` is the raw content, not yet serialized. This must be simple Python
data that renderers can handle (cf: dict, str, ...)
`renderers` is a list/tuple of renderer instances and represents the set of renderers
that the response can handle.
"""
# First argument taken by `SimpleTemplateResponse.__init__` is template_name, # First argument taken by `SimpleTemplateResponse.__init__` is template_name,
# which we don't need # which we don't need
super(Response, self).__init__(None, status=status) super(Response, self).__init__(None, status=status)
@ -132,9 +131,6 @@ class Response(SimpleTemplateResponse):
renderers=self.renderers) renderers=self.renderers)
def _get_renderers(self): def _get_renderers(self):
"""
This just provides a default when renderers havent' been set.
"""
if hasattr(self, '_renderers'): if hasattr(self, '_renderers'):
return self._renderers return self._renderers
return () return ()

View File

@ -1,7 +1,7 @@
Using the enhanced request in all your views Using the enhanced request in all your views
============================================== ==============================================
This example shows how you can use Django REST framework's enhanced `request` in your own views, without having to use the full-blown :class:`views.View` class. This example shows how you can use Django REST framework's enhanced `request` - :class:`request.Request` - in your own views, without having to use the full-blown :class:`views.View` class.
What can it do for you ? Mostly, it will take care of parsing the request's content, and handling equally all HTTP methods ... What can it do for you ? Mostly, it will take care of parsing the request's content, and handling equally all HTTP methods ...
@ -64,13 +64,12 @@ Now that you're convinced you need to use the enhanced request object, here is h
Base view enabling the usage of enhanced requests with user defined views. Base view enabling the usage of enhanced requests with user defined views.
""" """
parsers = parsers.DEFAULT_PARSERS parser_classes = parsers.DEFAULT_PARSERS
def dispatch(self, request, *args, **kwargs): def dispatch(self, request, *args, **kwargs):
self.request = request request = self.prepare_request(request)
request = self.get_request()
return super(MyBaseViewUsingEnhancedRequest, self).dispatch(request, *args, **kwargs) return super(MyBaseViewUsingEnhancedRequest, self).dispatch(request, *args, **kwargs)
And then, use this class as a base for all your custom views. And then, use this class as a base for all your custom views.
.. note:: you can also check the request example. .. note:: you can see this live in the examples.

View File

@ -21,11 +21,10 @@ class MyBaseViewUsingEnhancedRequest(RequestMixin, View):
Base view enabling the usage of enhanced requests with user defined views. Base view enabling the usage of enhanced requests with user defined views.
""" """
parsers = parsers.DEFAULT_PARSERS parser_classes = parsers.DEFAULT_PARSERS
def dispatch(self, request, *args, **kwargs): def dispatch(self, request, *args, **kwargs):
self.request = request request = self.prepare_request(request)
request = self.get_request()
return super(MyBaseViewUsingEnhancedRequest, self).dispatch(request, *args, **kwargs) return super(MyBaseViewUsingEnhancedRequest, self).dispatch(request, *args, **kwargs)