-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
108 lines (89 loc) · 3.16 KB
/
Copy pathserver.py
File metadata and controls
108 lines (89 loc) · 3.16 KB
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
from http.server import BaseHTTPRequestHandler, HTTPServer
import json
import os
from dataclasses import dataclass, asdict
TASKS_FILE = "tasks.txt"
@dataclass
class Task:
id: int
title: str
priority: str
isDone: bool = False
class TaskManager:
def __init__(self):
self.tasks = []
self.next_id = 1
self.load_tasks()
def load_tasks(self):
if os.path.exists(TASKS_FILE):
with open(TASKS_FILE, "r", encoding="utf-8") as f:
data = json.load(f)
for task_data in data:
task = Task(**task_data)
self.tasks.append(task)
if self.tasks:
self.next_id = max(task.id for task in self.tasks) + 1
def save_tasks(self):
with open(TASKS_FILE, "w", encoding="utf-8") as f:
json.dump([asdict(task) for task in self.tasks], f, ensure_ascii=False, indent=2)
def create_task(self, title, priority):
task = Task(id=self.next_id, title=title, priority=priority)
self.tasks.append(task)
self.next_id += 1
self.save_tasks()
return task
def complete_task(self, task_id):
for task in self.tasks:
if task.id == task_id:
task.isDone = True
self.save_tasks()
return True
return False
task_manager = TaskManager()
class TodoHandler(BaseHTTPRequestHandler):
def _send_json(self, data, status=200):
self.send_response(status)
self.send_header("Content-Type", "application/json")
self.end_headers()
self.wfile.write(json.dumps(data, ensure_ascii=False).encode())
def do_GET(self):
if self.path == "/tasks":
tasks = [asdict(task) for task in task_manager.tasks]
self._send_json(tasks)
else:
self.send_response(404)
self.end_headers()
def do_POST(self):
if self.path == "/tasks":
content_length = int(self.headers.get("Content-Length", 0))
body = self.rfile.read(content_length)
data = json.loads(body)
title = data.get("title")
priority = data.get("priority")
if not title or not priority:
self.send_response(400)
self.end_headers()
return
task = task_manager.create_task(title, priority)
self._send_json(asdict(task), 201)
elif self.path.startswith("/tasks/") and self.path.endswith("/complete"):
try:
task_id = int(self.path.split("/")[2])
except (IndexError, ValueError):
self.send_response(400)
self.end_headers()
return
if task_manager.complete_task(task_id):
self.send_response(200)
else:
self.send_response(404)
self.end_headers()
else:
self.send_response(404)
self.end_headers()
def run():
server = HTTPServer(("localhost", 8000), TodoHandler)
print("Server started on http://localhost:8000")
server.serve_forever()
if __name__ == "__main__":
run()