-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
72 lines (63 loc) · 2.1 KB
/
Copy pathapp.py
File metadata and controls
72 lines (63 loc) · 2.1 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
from flask import Flask, request, jsonify
import json
import os
app = Flask(__name__)
app.config['DATA_FILE'] = "tasks.json" # Χρησιμοποιούμε config αντί για global
# Βοηθητικές συναρτήσεις
def load_tasks():
file = app.config['DATA_FILE']
if not os.path.exists(file):
return []
with open(file, "r") as f:
return json.load(f)
def save_tasks(tasks):
file = app.config['DATA_FILE']
with open(file, "w") as f:
json.dump(tasks, f, indent=4)
def get_next_id(tasks):
if not tasks:
return 1
# Παίρνουμε το μεγαλύτερο υπάρχον id και προσθέτουμε 1
return max(task["id"] for task in tasks) + 1
# 1. Get all tasks
@app.route("/tasks", methods=["GET"])
def get_tasks():
tasks = load_tasks()
# Ταξινόμηση κατά id
tasks_sorted = sorted(tasks, key=lambda x: x["id"])
return jsonify(tasks_sorted), 200
# 2. Get task by id
@app.route("/tasks/<int:task_id>", methods=["GET"])
def get_task_by_id(task_id):
tasks = load_tasks()
for task in tasks:
if task["id"] == task_id:
return jsonify(task), 200
return jsonify({"error": "Task not found"}), 404
# 3. Create task
@app.route("/tasks", methods=["POST"])
def create_task():
tasks = load_tasks()
data = request.get_json()
new_task = {
"id": get_next_id(tasks),
"username": data["username"],
"title": data["title"],
"description": data["description"],
"deadline": data["deadline"]
}
tasks.append(new_task)
save_tasks(tasks)
return jsonify(new_task), 201
# 4. Delete task
@app.route("/tasks/<int:task_id>", methods=["DELETE"])
def delete_task(task_id):
tasks = load_tasks()
for task in tasks:
if task["id"] == task_id:
tasks.remove(task)
save_tasks(tasks)
return jsonify({"message": "Task deleted"}), 200
return jsonify({"error": "Task not found"}), 404
if __name__ == "__main__":
app.run(debug=True)