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)