-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
64 lines (50 loc) · 1.59 KB
/
server.py
File metadata and controls
64 lines (50 loc) · 1.59 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
from dataclasses import dataclass
from typing import Dict
from flask import Flask, request, jsonify
import logging
# Logger configuration
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)
# To-do record class
@dataclass
class TodoRecord:
content: str
is_complete: bool
# In-memory database
database: Dict[int, TodoRecord] = {}
id_counter: int = 0
# Flask app initialization
app = Flask(__name__)
# Create a new to-do
@app.route('/', methods=['POST'])
def create_todo():
record = TodoRecord(
content=request.json['content'],
is_complete=request.json['is_complete']
)
global id_counter
id_counter += 1
record.id = id_counter
database[record.id] = record
logger.info(f"Successfully created to-do {record.id}")
return jsonify({'id': record.id}), 200
# Get an existing to-do by ID
@app.route('/<int:id>', methods=['GET'])
def get_todo(id):
record = database.get(id)
if record is None:
logger.info(f"Unable to get to-do {id} as it was not found")
return jsonify({'error': 'not found'}), 404
logger.info(f"Successfully got to-do {id} - returning {record}")
return jsonify(record), 200
# Delete an existing to-do by ID
@app.route('/<int:id>', methods=['DELETE'])
def delete_todo(id):
if database.pop(id, None) is None:
logger.info(f"Failed to delete to-do {id} as it was not found")
return jsonify({'error': 'not found'}), 404
logger.info(f"Successfully deleted to-do {id}")
return jsonify({'success': True}), 200
# Run the Flask app
if __name__ == '__main__':
app.run(debug=True)