-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapp.py
117 lines (81 loc) · 2.44 KB
/
app.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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
from flask import Flask, request
from model import Ticket
from datetime import datetime
from db_manip import *
import json
app = Flask(__name__)
init_db()
@app.route("/")
def show_endpoints_list():
"""
Displays the list of endpoints(as static html).
"""
return (
"<p>Endpooints</p>"
+ "<p>List all tickets: /getall</p>"
+ "<p>List all tickets in order: /getall/ordered</p>"
+ "<p>Get specific ticket: /get<uuid></p>"
+ "<p>Add a ticket: /add</p>"
+ "<p>Edit a ticket: /edit<uuid></p>"
)
@app.get("/getall")
def get_all_tickets():
"""
Returns a list of all ticket entries.
"""
all_entries = []
for row in get_all_entries():
entry = strings_to_objects(row)
ticket = Ticket(*entry).as_json()
all_entries.append(ticket)
return all_entries
@app.get("/getall/ordered")
def get_all_tickets_ordered():
"""
Returns a list of all ticket entries in order of time of creation.
"""
entries = get_all_tickets()
sorted_entries = sorted(
entries, key=lambda entry: datetime.fromisoformat(entry["created_at"])
)
return sorted_entries
@app.get("/get<idstr>")
def get_one(idstr):
"""
Returns the ticket entry with the provided UUID.
"""
entry = get_entry(idstr)
if not entry:
return (f"Ticket ID {idstr} could not be found.", 404)
ticket = strings_to_objects(entry)
return Ticket(*ticket).as_json()
@app.post("/add")
def add_ticket():
"""
Adds a ticket entry to the database.
"""
body: dict = request.get_json()
ticket = objects_to_strings(body)
insert_entry(ticket)
return "Ticket has been added."
@app.post("/edit<idstr>")
def edit_ticket(idstr: str):
"""
Edits a ticket entry in the database.
"""
body: dict = request.get_json()
ticket = objects_to_strings(body)
edit_entry(ticket, idstr)
return f"Ticket ID {idstr} has been updated."
def objects_to_strings(ticket: dict) -> dict:
"""Serialize objects in the ticket to strings."""
ticket = ticket.copy()
ticket["tags"] = json.dumps(ticket["tags"])
ticket["contents"] = json.dumps(ticket["contents"])
return ticket
def strings_to_objects(query_row: tuple) -> tuple:
"""Deserialize strings in the query to objects."""
query_row = list(query_row)
query_row[1] = json.loads(query_row[1])
query_row[2] = json.loads(query_row[2])
return tuple(query_row)