User:Babbage Linden/Django/Content Negotiation

From Second Life Wiki
Revision as of 08:49, 2 December 2008 by Babbage Linden (talk | contribs) (New page: Content negotiation was also very simple to add based on a [http://www.b-list.org/weblog/2008/nov/29/multiresponse/ blog post]. <pre> formatters = {'application/llsd+binary': llsd.format_...)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

Content negotiation was also very simple to add based on a blog post.

formatters = {'application/llsd+binary': llsd.format_binary,
              'application/llsd+notation': llsd.format_notation,
              'application/llsd+xml': llsd.format_xml,
              'application/xml': llsd.format_xml}

parsers = {'application/llsd+binary': llsd.parse_binary,
           'application/llsd+notation': llsd.parse_notation,
           'application/llsd+xml': llsd.parse_xml,
           'application/xml': llsd.parse_xml}

def negotiate_content(func):
    def wrapper(request, *args, **kwargs):
        if request.raw_post_data:
            request_type = request.META.get('CONTENT_TYPE', 'application/xml')
            parser = parsers.get(request_type, llsd.parse_xml)
            request.data = parser(request.raw_post_data)
        response_data = func(request, *args, **kwargs)
        response_type = request.META.get('HTTP_ACCEPT', 'application/xml')
        formatter = formatters.get(response_type, llsd.format_xml)
        return HttpResponse(formatter(response_data))
    return wrapper

Which allows handlers to be decorated like this:

@negotiate_content
def region_GET(request, region_id):
    #...