How to serve Template or do Redirect on Error? "Template / Redirect" object is not callable ! #1645
-
input from pathlib import Path
from litestar import Litestar, Request, get
from litestar.contrib.jinja import JinjaTemplateEngine
from litestar.response_containers import Template, Redirect
from litestar.template.config import TemplateConfig
@get("/home")
async def aaa() -> str:
return 'home!'
@get("/template")
async def bbb() -> Template:
return Template(name="abc.html")
def show_template_on_error(_: Request, __: Exception) -> Template:
return Template(name="abc.html")
@get("/template-error", exception_handlers={Exception: show_template_on_error})
async def ccc() -> str:
1 / 0
return ''
@get("/redirect")
async def ddd() -> Redirect:
return Redirect(path='/home', status_code=302)
def redirect_on_error(_: Request, __: Exception) -> Redirect:
return Redirect(path='/home', status_code=302)
@get("/redirect-error", exception_handlers={Exception: redirect_on_error})
async def eee() -> str:
1 / 0
return ''
app = Litestar(route_handlers=[aaa, bbb, ccc, ddd, eee],
template_config=TemplateConfig(directory=Path(__file__).parent, engine=JinjaTemplateEngine))
if __name__ == '__main__':
import uvicorn
uvicorn.run('0:app') curl Microsoft Windows [Version 10.0.19044.2846]
(c) Microsoft Corporation. All rights reserved.
C:\Users\User-PC>curl http://127.0.0.1:8000/template
<p> I am abc</p>
C:\Users\User-PC>curl http://127.0.0.1:8000/template-error
{"status_code":500,"detail":"TypeError(\"'Template' object is not callable\")"}
C:\Users\User-PC>curl http://127.0.0.1:8000/home
home!
C:\Users\User-PC>curl http://127.0.0.1:8000/redirect -L
home!
C:\Users\User-PC>curl http://127.0.0.1:8000/redirect-error
{"status_code":500,"detail":"TypeError(\"'Redirect' object is not callable\")"}
C:\Users\User-PC> logs
|
Beta Was this translation helpful? Give feedback.
Answered by
Goldziher
May 10, 2023
Replies: 2 comments 9 replies
This comment was marked as disruptive content.
This comment was marked as disruptive content.
-
An exception handler should return a response. Instead if |
Beta Was this translation helpful? Give feedback.
9 replies
Answer selected by
4n1qz5skwv
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
An exception handler should return a response. Instead if
Template
return aTemplateResponse