11from fastapi import FastAPI
22from fastapi import HTTPException
3-
3+ from storage import TaskStorage
44app = FastAPI ()
5- tasks = []
6- task_id_counter = 1
5+ storage = TaskStorage ()
76# we display a list of all received tasks.
87@app .get ("/tasks" )
98def get_tasks ():
10- return tasks
9+ return storage . load ()
1110# We add a new task, add it to the task list, and increment the id counter.
1211@app .post ("/tasks" )
1312def create_task (name : str , condition : str = 'new' ):
14- global task_id_counter
15- task = {'id' : task_id_counter , 'name' : name , 'condition' : condition }
13+ tasks = storage .load ()
14+ new_id = max ((task ['id' ] for task in tasks ), start = 0 ) + 1
15+ task = {'id' : new_id , 'name' : name , 'condition' : condition }
1616 tasks .append (task )
17- task_id_counter += 1
17+ storage . save ( tasks )
1818 return task
1919# We update the task; if the task is missing, we raise an error.
2020@app .put ("/tasks/{task_id}" )
21- def update_task (task_id : int , name :str , condition : str ):
21+ def update_task (task_id : int , name : str , condition : str ):
22+ tasks = storage .load ()
2223 for task in tasks :
2324 if task ['id' ] == task_id :
24- task [name ] = name
25- task [condition ] = condition
26- return task
25+ task ['name' ] = name
26+ task ['condition' ] = condition
27+ storage .save (tasks )
28+ return task
2729 raise HTTPException (status_code = 404 , detail = 'task not found' )
2830# We search for a task by ID, if we find it, we delete it, if not, we raise an error
2931@app .delete ("/tasks/{task_id}" )
3032def delete_task (task_id : int ):
33+ tasks = storage .load ()
3134 for task in tasks :
3235 if task ['id' ] == task_id :
3336 tasks .remove (task )
37+ storage .save (tasks )
3438 return 'task deleted'
3539 raise HTTPException (status_code = 404 , detail = 'task not found' )
0 commit comments