Skip to content

Commit 47e501d

Browse files
committed
add taskstorage and json file. del task list and fix bugs
1 parent 2204746 commit 47e501d

File tree

2 files changed

+28
-11
lines changed

2 files changed

+28
-11
lines changed
Lines changed: 15 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,35 +1,39 @@
11
from fastapi import FastAPI
22
from fastapi import HTTPException
3-
3+
from storage import TaskStorage
44
app = FastAPI()
5-
tasks = []
6-
task_id_counter = 1
5+
storage = TaskStorage()
76
# we display a list of all received tasks.
87
@app.get("/tasks")
98
def 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")
1312
def 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}")
3032
def 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')
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
import json
2+
import os
3+
class TaskStorage:
4+
def __init__(self, filename: str = 'tasks.json'):
5+
self.file = filename
6+
if not os.path.exists(self.file): # if file does not exist, create file with empty list
7+
self.save([])
8+
def load(self):
9+
with open(self.file, 'r', encoding = 'utf-8') as f:
10+
return json.load(f)
11+
def save(self, tasks):
12+
with open(self.file, 'w', encoding = 'utf-8') as f:
13+
json.dump(tasks, f)

0 commit comments

Comments
 (0)