Skip to content

Instantly share code, notes, and snippets.

@Rooba
Created September 18, 2022 15:54
Show Gist options
  • Save Rooba/01915deea631f9cdb33e7d5ba4a3fea5 to your computer and use it in GitHub Desktop.
Save Rooba/01915deea631f9cdb33e7d5ba4a3fea5 to your computer and use it in GitHub Desktop.
wrapper which works for normal views and class based views
from typing import Callable
from sanic.blueprints import Blueprint
from sanic.request import Request
from sanic import Sanic, text
from sanic.response import HTTPResponse
from sanic.views import HTTPMethodView
from sanic_ext.extensions.templating import render
def template(
template_name: str,
login_req: bool = False,
blueprint: Blueprint | None = None,
uri: str | None = None,
):
def sub_wrap(fn: Callable | type):
async def wrapped(*args, **kwargs):
obj, request = None, None
response = {}
if isinstance(args[0], Request):
request = args[0]
args = args[1:]
else:
obj = args[0]
request = args[1]
args = args[2:]
if obj:
response = await fn(obj, request, *args, **kwargs)
else:
response = await fn(request, *args, **kwargs)
if isinstance(response, dict):
return await render.render(
template_name=template_name, status=200, context=response
)
elif isinstance(response, HTTPResponse):
return response
else:
return text(response)
if fn.__doc__:
wrapped.__doc__ = fn.__doc__
else:
wrapped.__doc__ = "".join([f.title() for f in fn.__name__.split("_")])
wrapped.__name__ = fn.__name__
sanic = Sanic.get_app()
if isinstance(fn, type) and issubclass(fn, HTTPMethodView):
if not hasattr(fn, "uri") and not uri:
raise AttributeError(
f"'{fn}' should have attribute 'uri' or uri should be passed to 'template'"
)
else:
_uri = uri or getattr(fn, "uri")
if not hasattr(fn, "blueprint") and not blueprint:
_bp = sanic
else:
_bp = blueprint or getattr(fn, "blueprint")
for k, v in fn.__dict__.items():
if k in ["get", "post", "put", "patch", "delete", "head"]:
setattr(fn, k, template(template_name)(v))
_bp.add_route(fn.as_view(), _uri)
return wrapped
return sub_wrap
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment