-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathroutes.py
62 lines (41 loc) · 1.78 KB
/
routes.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
from fastapi import APIRouter, BackgroundTasks, HTTPException
from sqlalchemy.exc import NoResultFound
from celery_app import add_task
from repository import TaskRepository
from schemas import Task, TaskAdd
router = APIRouter(
prefix='/tasks',
tags=['Tasks']
)
@router.post('', response_model=Task)
async def post_task(task: TaskAdd, background_tasks: BackgroundTasks) -> Task:
new_task = await TaskRepository.add_data(task)
background_tasks.add_task(add_task.delay, task.name, task.description)
return new_task
@router.get('')
async def get_tasks() -> list[Task]:
tasks = await TaskRepository.get_data()
return tasks
@router.get('/{task_id}', response_model=Task)
async def get_task_by_id(task_id: int) -> Task:
task = await TaskRepository.get_task_by_id(task_id)
return task
@router.put('/{task_id}', response_model=Task)
async def update_task(task_id: int, task_data: TaskAdd) -> Task:
updated_task = await TaskRepository.update_data(task_id, task_data)
if not updated_task:
raise HTTPException(status_code=404, detail="Task not found!")
return updated_task
@router.patch('/{task_id}', response_model=Task)
async def patch_task(task_id: int, task_data: TaskAdd) -> Task:
try:
updated_task = await TaskRepository.patch_data(task_id, task_data.dict(exclude_unset=True))
return updated_task
except NoResultFound:
raise HTTPException(status_code=404, detail=f"Task with id {task_id} not found!")
@router.delete('/{task_id}')
async def delete_task(task_id: int):
deleted = await TaskRepository.delete_data(task_id)
if not deleted:
raise HTTPException(status_code=404, detail="Task not found!")
return {"message": "Task deleted!"}