diff --git a/fastapi_chameleon/engine.py b/fastapi_chameleon/engine.py index d06ef8b..dd912da 100644 --- a/fastapi_chameleon/engine.py +++ b/fastapi_chameleon/engine.py @@ -1,7 +1,7 @@ import inspect import os from functools import wraps -from typing import Optional +from typing import Optional, Union, Callable import fastapi from chameleon import PageTemplateLoader, PageTemplate @@ -49,7 +49,7 @@ def response(template_file: str, mimetype='text/html', status_code=200, **templa return fastapi.Response(content=html, media_type=mimetype, status_code=status_code) -def template(template_file: Optional[str] = None, mimetype: str = 'text/html'): +def template(template_file: Optional[Union[Callable, str]] = None, mimetype: str = 'text/html'): """ Decorate a FastAPI view method to render an HTML response. @@ -58,6 +58,11 @@ def template(template_file: Optional[str] = None, mimetype: str = 'text/html'): :return: Decorator to be consumed by FastAPI """ + wrapped_function = None + if callable(template_file): + wrapped_function = template_file + template_file = None + def response_inner(f): nonlocal template_file global template_path @@ -92,7 +97,7 @@ def template(template_file: Optional[str] = None, mimetype: str = 'text/html'): else: return sync_view_method - return response_inner + return response_inner(wrapped_function) if wrapped_function else response_inner def __render_response(template_file, response_val, mimetype): diff --git a/tests/test_render.py b/tests/test_render.py index 300f156..3d08043 100644 --- a/tests/test_render.py +++ b/tests/test_render.py @@ -42,6 +42,18 @@ def test_default_template_name_pt(): assert '

Hello default WORLD!

' in html +def test_default_template_name_no_parentheses(): + @fc.template + def index(a, b, c): + return {'a': a, 'b': b, 'c': c, 'world': 'WORLD'} + + resp = index(1, 2, 3) + assert isinstance(resp, fastapi.Response) + assert resp.status_code == 200 + html = resp.body.decode('utf-8') + assert '

Hello default WORLD!

' in html + + def test_default_template_name_html(): @fc.template() def details(a, b, c):