Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
from django.http import HttpResponse
import json
import mf2py
from rdflib import Graph
def parse_accept_header(accept):
"""Parse the Accept header *accept*, returning a list with pairs of
(media_type, q_value), ordered by q values.
"""
result = []
for media_range in accept.split(","):
parts = media_range.split(";")
media_type = parts.pop(0)
media_params = []
q = 1.0
for part in parts:
(key, value) = part.lstrip().split("=", 1)
if key == "q":
q = float(value)
else:
media_params.append((key, value))
result.append((media_type, tuple(media_params), q))
result.sort(lambda x, y: -cmp(x[2], y[2]))
return result
class RdfMiddleware(object):
def process_response(self, request, response):
accept = parse_accept_header(request.META.get("HTTP_ACCEPT", ""))
if len(accept) > 0:
for media_type, params, q_value in accept:
if media_type == "text/html":
return response
elif media_type == "application/xhtml+xml":
return response
elif media_type == "text/n3":
ctype = "text/n3; charset=\"UTF-8\""
return self._process_rdf(request, response, 'n3', ctype)
elif media_type == "text/turtle":
ctype = "text/turtle; charset=\"UTF-8\""
return self._process_rdf(request, response, 'turtle', ctype)
elif media_type == "text/ntriples":
ctype = "text/ntriples; charset=\"UTF-8\""
return self._process_rdf(request, response, 'nt', ctype)
elif media_type == "application/rdf+xml":
return self._process_rdf(request, response, 'xml')
elif media_type == "application/ld+json":
return self._process_json_ld(request, response)
elif media_type == "application/json":
return self._process_uf2(request, response)
else:
return response
else:
return response
def _process_rdf(self, request, response, format, ctype=None):
body = response.rendered_content
g = Graph()
# TODO: pass in URL context
g.parse(data=body, format='rdfa')
# TODO: set headers
return HttpResponse(g.serialize(format=format), headers)
def _process_json_ld(self, request, response):
return response
def _process_uf2(self, request, response):
body = response.rendered_content
# TODO: pass in URL context
data = mf2py.parse(doc=body)
return HttpResponse(json.dumps(data, indent=2))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment