Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Template: reuse LazyResponse for rendered response #244

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 5 additions & 5 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,16 +27,16 @@ If you want to run all tests without install `dev` requirements, you can install
pip install -e .['test']
```

To run tests, use `test` command with `setup.py`:
To run tests, use `pytest`:

```shell
python setup.py test
pytest
```

Or, use `pytest` with customize options like:

```shell
pytest tests/test_openapi.py --maxfail=1
pytest tests/extensions/openapi/ --maxfail=1
```

Furthermore, you can use `tox` to run tests with different environment configs to verify compatibility.
Expand Down Expand Up @@ -82,8 +82,8 @@ In `dev` requirements, some modules related to code style are already included:
Please make sure your contribution will using the same styling tools. You can use following commands to apply them to your contributions:

```shell
black --verbose sanic_openapi tests
isort --recursive sanic_openapi tests
black --verbose sanic_ext tests
isort --recursive sanic_ext tests
```

## Build Document
Expand Down
42 changes: 23 additions & 19 deletions sanic_ext/extensions/templating/engine.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,7 @@
from sanic.request import Request
from sanic.response import HTTPResponse

from sanic_ext.extensions.templating.render import (
LazyResponse,
TemplateResponse,
)

from sanic_ext.extensions.templating.render import LazyResponse, TemplateResponse

if TYPE_CHECKING:
from sanic_ext import Config
Expand Down Expand Up @@ -42,13 +38,13 @@ def template(
def decorator(f):
@wraps(f)
async def decorated_function(*args, **kwargs):
context = f(*args, **kwargs)
if isawaitable(context):
context = await context
if isinstance(context, HTTPResponse) and not isinstance(
context, TemplateResponse
response = f(*args, **kwargs)
if isawaitable(response):
response = await response
if isinstance(response, HTTPResponse) and not isinstance(
response, TemplateResponse
):
return context
return response

# TODO
# - Allow each of these to be a callable that is executed here
Expand All @@ -57,21 +53,29 @@ async def decorated_function(*args, **kwargs):
"content_type": content_type,
"headers": headers,
}

if isinstance(context, LazyResponse):
for attr in ("status", "headers", "content_type"):
value = getattr(context, attr, None)
if value:
params[attr] = value
context = context.context
context = {}

if isinstance(response, LazyResponse):
context = response.context
elif isinstance(response, dict):
context = response
response = HTTPResponse(**params)
else:
raise TypeError(
"A templated view must return a dict or HTTPResponse."
)

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

content = render(**context)
if isawaitable(content):
content = await content

return HTTPResponse(content, **params)
if isinstance(content, str):
content = content.encode()
response.body = content

return response

return decorated_function

Expand Down
14 changes: 14 additions & 0 deletions tests/extensions/templating/test_templating.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,14 @@ async def handler3(_):
context={"seq": ["five", "six"]}, status=201, app=app
)

@app.get("/4")
async def handler4(_):
response = await render(
"foo.html", context={"seq": ["three", "four"]}, app=app
)
response.add_cookie("test", "foobar")
return response

_, response = app.test_client.get("/1")
assert response.content_type == "text/html; charset=utf-8"
assert "<li>one</li>" in response.text
Expand All @@ -47,6 +55,12 @@ async def handler3(_):
assert "<li>six</li>" in response.text
assert response.status == 201

_, response = app.test_client.get("/4")
assert response.content_type == "text/html; charset=utf-8"
assert "<li>three</li>" in response.text
assert "<li>four</li>" in response.text
assert response.cookies.get("test") == "foobar"


def test_render_from_string():
app = Sanic("templating-from-string")
Expand Down