-
Notifications
You must be signed in to change notification settings - Fork 0
/
web.py
99 lines (71 loc) · 2.35 KB
/
web.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
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
from typing import Dict, List
from flask import Flask, request
from flask_restful import Api, Resource
app = Flask(__name__)
api = Api(app)
tasks = [
{
'id': 1,
'title': "Aller à l'épicerie",
'done': False
},
# {
# 'id': 2,
# 'title': "Étudier pour l'examen d'électromag",
# 'done': False
# }
]
class HelloResource(Resource):
def get(self):
return {'message': 'Bonjour le monde!'}
class TodosResource(Resource):
def __init__(self, tasks):
self.tasks = tasks
def get(self):
return tasks
def post(self):
ids = [task['id'] for task in self.tasks]
new_id = max(ids) + 1
if 'title' not in request.form:
return {'error': 'Must provide "title" data'}, 400
if 'done' in request.form:
done = bool(request.form['done'])
else:
done = False
self.tasks.append(
{
'id': new_id,
'title': request.form['title'],
'done': done
}
)
return {'message': 'Tâche ajoutée'}, 201
class TodoResource(Resource):
def __init__(self, tasks: List[Dict]):
self.tasks = tasks
def get(self, task_id):
for task in self.tasks:
if task['id'] == task_id:
return task
return {'error': f'Task ID "{task_id}" not found'}, 404
def put(self, task_id):
if 'done' in request.form:
done = request.form['done']
else:
return {'error': 'Must provide "done" data, ex. {"done": true}'}, 400
for task in self.tasks:
if task['id'] == task_id:
task['done'] = done
return {'message': f'"{task_id}" updated'}, 200
return {'error': f'Not Found: "{task_id}"'}, 404
def delete(self, task_id):
for i, task in enumerate(self.tasks):
if task['id'] == task_id:
del self.tasks[i]
return {'message': 'Deleted'}, 200
return {'error': f'Not Found: "{task_id}"'}, 404
api.add_resource(HelloResource, '/hello_world')
api.add_resource(TodosResource, '/todo', resource_class_kwargs={'tasks': tasks})
api.add_resource(TodoResource, '/todo/<int:task_id>', resource_class_kwargs={'tasks': tasks})
if __name__ == '__main__':
app.run(debug=True)