Middleware class to properly format arbitrary data

23 views
Skip to first unread message

Kevin

unread,
Feb 14, 2012, 6:14:38 AM2/14/12
to Django users
Hello everyone,

Before I go ahead and build a simple middleware for this myself, I
would like to know if such a middleware already exists in the wild, so
that I can prevent re-inventing the wheel. Here's an example, if
nobody is following what the subject actually means:

Say I have a view that does not return a django.http.HTTPResponse
object. Instead, it returns a dictionary or a file-like object. I
would like said middleware to detect this and format the output data
accordingly. In the case of a dictionary, it will automatically add a
JSON header, encode the dictionary and output it. For the sake of a
file-like object, it will use it's .read() method to provide the
output data. I would also like it to check if a Form object is being
returned and automatically provide a template and a RequestContext.

According to a DRY principle, this type of feature only makes sense to
have built into Django. However, if I attempt to return anything but
an HTTPResponse object, I get a big fat exception saying that it just
won't work, and I need to manually construct my HTTPResponse object
specifically for my data. Constructing HTTPResponses and Contexts is
one of my most hated parts of Django, it's not really fun and get's
very repetitive and old really fast.

Thanks.

Tom Evans

unread,
Feb 14, 2012, 6:29:12 AM2/14/12
to django...@googlegroups.com
On Tue, Feb 14, 2012 at 11:14 AM, Kevin <kver...@gmail.com> wrote:
> Hello everyone,
>
>  Before I go ahead and build a simple middleware for this myself, I
> would like to know if such a middleware already exists in the wild, so
> that I can prevent re-inventing the wheel.  Here's an example, if
> nobody is following what the subject actually means:
>

Why would you do it as middleware? This would mean two things:

1) The middleware will have to do lots of nasty isinstance/other type checking.
2) You break the contract of what a view is - a view is a callable
returning a response. Your 'view' functions will just be random
functions returning arbitrary objects, which may or may not be
translated into a response by middleware. Hacky.

Instead, simply subclass HttpResponse, and make it do what you want it
to do. As an example, as your specified use case was to simplify
generating JSON responses, I give you JSONResponse:

http://djangosnippets.org/snippets/154/

Cheers

Tom

Reply all
Reply to author
Forward
0 new messages