Skip to content

Commit fd9513a

Browse files
committed
Template: reuse LazyResponse for rendered response
Previously, only status, headers, and content type are passed to the final rendered response. After this change, the LazyResponse is preserved and only has its body changed after rendering. This allows for, e.g., setting cookie for the LazyResponse.
1 parent 7ab93d9 commit fd9513a

File tree

1 file changed

+16
-10
lines changed

1 file changed

+16
-10
lines changed

sanic_ext/extensions/templating/engine.py

+16-10
Original file line numberDiff line numberDiff line change
@@ -42,13 +42,13 @@ def template(
4242
def decorator(f):
4343
@wraps(f)
4444
async def decorated_function(*args, **kwargs):
45-
context = f(*args, **kwargs)
45+
response = f(*args, **kwargs)
4646
if isawaitable(context):
47-
context = await context
47+
response = await context
4848
if isinstance(context, HTTPResponse) and not isinstance(
49-
context, TemplateResponse
49+
response, TemplateResponse
5050
):
51-
return context
51+
return response
5252

5353
# TODO
5454
# - Allow each of these to be a callable that is executed here
@@ -57,20 +57,26 @@ async def decorated_function(*args, **kwargs):
5757
"content_type": content_type,
5858
"headers": headers,
5959
}
60+
context = {}
6061

61-
if isinstance(context, LazyResponse):
62-
for attr in ("status", "headers", "content_type"):
63-
value = getattr(context, attr, None)
64-
if value:
65-
params[attr] = value
66-
context = context.context
62+
if isinstance(response, LazyResponse):
63+
context = response.context
64+
elif isinstance(response, dict):
65+
context = response
66+
response = HTTPResponse(**params)
67+
else:
68+
raise TypeError("A templated view must return a dict or HTTPResponse.")
6769

6870
context["request"] = Request.get_current()
6971

7072
content = render(**context)
7173
if isawaitable(content):
7274
content = await content
7375

76+
if isinstance(content, str):
77+
content = content.encode()
78+
response.body = content
79+
7480
return HTTPResponse(content, **params)
7581

7682
return decorated_function

0 commit comments

Comments
 (0)