Created
October 18, 2023 10:04
-
-
Save jfjensen/6f292b47c8304dcd134b2a49f16e807c to your computer and use it in GitHub Desktop.
An example using a Jinja template with the Litestar framework for Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from litestar import Litestar, get | |
from litestar.contrib.jinja import JinjaTemplateEngine | |
from litestar.response import Template | |
from litestar.template.config import TemplateConfig | |
from litestar.exceptions import HTTPException | |
from pydantic import BaseModel | |
class User(BaseModel): | |
user_id: int | |
name: str | |
age: int | |
email: str | |
DUMMY_USER_STORE: list[User] = [ | |
User(user_id=1, name="John Doe", age=30, email="[email protected]"), | |
User(user_id=2, name="Jane Doe", age=25, email="[email protected]") | |
] | |
@get("/user/{user_id:int}") | |
async def user(user_id: int) -> Template: | |
user = [u for u in DUMMY_USER_STORE if u.user_id == user_id] | |
if len(user)>0: | |
name = user[0].name | |
return Template(template_name="user.html", context={"name": name}) | |
else: | |
raise HTTPException(status_code=400, detail="User not found") | |
@get("/users") | |
async def users() -> Template: | |
users=DUMMY_USER_STORE | |
return Template(template_name="users.html", context={"users": users}) | |
app = Litestar( | |
route_handlers=[user, users], | |
template_config=TemplateConfig(directory=".\\templates", engine=JinjaTemplateEngine), | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment