1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
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)
|