Created
October 20, 2023 16:27
-
-
Save jfjensen/fb039a98eff7352b223d101a1bb7f8b3 to your computer and use it in GitHub Desktop.
A simple web application using the Litestar web framework, with basic CRUD operations for managing user data
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 dataclasses import dataclass | |
from litestar import Litestar, get, post, delete | |
from litestar.exceptions import HTTPException | |
@dataclass | |
class User(): | |
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]") | |
] | |
@post(path="/user") | |
async def create_user(data: User) -> User: | |
# Logic to create a user | |
user = [u for u in DUMMY_USER_STORE if u.user_id == data.user_id] | |
if len(user) > 0: | |
return False | |
else: | |
DUMMY_USER_STORE.append(data) | |
return data | |
@get(path="/users") | |
async def list_users() -> list[User]: | |
# Logic to list all users | |
all_users = DUMMY_USER_STORE | |
return all_users | |
@get(path="/user/{user_id:int}") | |
async def get_user(user_id: int) -> User: | |
# Logic to retrieve a user by ID | |
user = [u for u in DUMMY_USER_STORE if u.user_id == user_id] | |
if len(user)==0: | |
raise HTTPException(status_code=400, detail=f"user with id [{user_id}] not found") | |
else: | |
return user | |
@delete(path="/user/{user_id:int}") | |
async def delete_user(user_id: int) -> None: | |
# Logic to delete a user by ID | |
temp = DUMMY_USER_STORE.copy() | |
DUMMY_USER_STORE.clear() | |
for u in temp: | |
if u.user_id != user_id: | |
DUMMY_USER_STORE.append(u) | |
return None | |
app = Litestar(route_handlers=[create_user, list_users, get_user, delete_user]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment