summaryrefslogtreecommitdiff
path: root/sw/util.py
diff options
context:
space:
mode:
Diffstat (limited to 'sw/util.py')
-rw-r--r--sw/util.py43
1 files changed, 43 insertions, 0 deletions
diff --git a/sw/util.py b/sw/util.py
new file mode 100644
index 0000000..de80466
--- /dev/null
+++ b/sw/util.py
@@ -0,0 +1,43 @@
+from flask import request, abort, Response, render_template
+
+from jinja2.exceptions import TemplateNotFound
+
+
+def decide_response_filetype():
+ res = request.accept_mimetypes.best_match(
+ [
+ "text/html",
+ "application/ld+json",
+ "application/json",
+ ]
+ )
+
+ if not request.accept_mimetypes:
+ return (".json", "application/ld+json")
+
+ elif res == "text/html":
+ return (".html", "text/html")
+
+ elif res == "application/json":
+ return (".json", "application/json")
+
+ elif res == "application/ld+json":
+ return (".json", "application/ld+json")
+
+ else: # res is None
+ abort(406)
+
+
+def prepared_output(filename, status=200, **kwargs):
+ ext, mime = decide_response_filetype()
+
+ try:
+ body = render_template(f"{filename}{ext}", **kwargs)
+
+ except TemplateNotFound:
+ # TODO
+ # Should probably try the other file extensions available
+ # rather than error out if the first one fails
+ abort(406)
+
+ return Response(body, content_type=mime, status=status)