User:Babbage Linden/Django/Content Negotiation

From Second Life Wiki
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):
    #...