-
Notifications
You must be signed in to change notification settings - Fork 64
/
mail_server.py
148 lines (119 loc) · 4.05 KB
/
mail_server.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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
from typing import Dict, List, Optional
from flask import Flask, request, jsonify
import pathlib
import uuid
import json
app = Flask(__name__)
thisdir = pathlib.Path(__file__).parent.absolute() # path to directory of this file
# Function to load and save the mail to/from the json file
def load_mail() -> List[Dict[str, str]]:
"""
Loads the mail from the json file
Returns:
list: A list of dictionaries representing the mail entries
"""
try:
return json.loads(thisdir.joinpath('mail_db.json').read_text())
except FileNotFoundError:
return []
def save_mail(mail: List[Dict[str, str]]) -> None:
"""TODO: fill out this docstring (using the load_mail docstring as a guide)
"""
thisdir.joinpath('mail_db.json').write_text(json.dumps(mail, indent=4))
def add_mail(mail_entry: Dict[str, str]) -> str:
"""TODO: fill out this docstring (using the load_mail docstring as a guide)
"""
mail = load_mail()
mail.append(mail_entry)
mail_entry['id'] = str(uuid.uuid4()) # generate a unique id for the mail entry
save_mail(mail)
return mail_entry['id']
def delete_mail(mail_id: str) -> bool:
"""TODO: fill out this docstring (using the load_mail docstring as a guide)
"""
mail = load_mail()
for i, entry in enumerate(mail):
if entry['id'] == mail_id:
mail.pop(i)
save_mail(mail)
return True
return False
def get_mail(mail_id: str) -> Optional[Dict[str, str]]:
"""TODO: fill out this docstring (using the load_mail docstring as a guide)
"""
mail = load_mail()
for entry in mail:
if entry['id'] == mail_id:
return entry
return None
def get_inbox(recipient: str) -> List[Dict[str, str]]:
"""TODO: fill out this docstring (using the load_mail docstring as a guide)
"""
mail = load_mail()
inbox = []
for entry in mail:
if entry['recipient'] == recipient:
inbox.append(entry)
return inbox
def get_sent(sender: str) -> List[Dict[str, str]]:
"""TODO: fill out this docstring (using the load_mail docstring as a guide)
"""
mail = load_mail()
sent = []
for entry in mail:
if entry['sender'] == sender:
sent.append(entry)
return sent
# API routes - these are the endpoints that the client can use to interact with the server
@app.route('/mail', methods=['POST'])
def add_mail_route():
"""
Summary: Adds a new mail entry to the json file
Returns:
str: The id of the new mail entry
"""
mail_entry = request.get_json()
mail_id = add_mail(mail_entry)
res = jsonify({'id': mail_id})
res.status_code = 201 # Status code for "created"
return res
@app.route('/mail/<mail_id>', methods=['DELETE'])
def delete_mail_route(mail_id: str):
"""
Summary: Deletes a mail entry from the json file
Args:
mail_id (str): The id of the mail entry to delete
Returns:
bool: True if the mail was deleted, False otherwise
"""
# TODO: implement this function
pass # remove this line
@app.route('/mail/<mail_id>', methods=['GET'])
def get_mail_route(mail_id: str):
"""
Summary: Gets a mail entry from the json file
Args:
mail_id (str): The id of the mail entry to get
Returns:
dict: A dictionary representing the mail entry if it exists, None otherwise
"""
res = jsonify(get_mail(mail_id))
res.status_code = 200 # Status code for "ok"
return res
@app.route('/mail/inbox/<recipient>', methods=['GET'])
def get_inbox_route(recipient: str):
"""
Summary: Gets all mail entries for a recipient from the json file
Args:
recipient (str): The recipient of the mail
Returns:
list: A list of dictionaries representing the mail entries
"""
res = jsonify(get_inbox(recipient))
res.status_code = 200
return res
# TODO: implement a rout e to get all mail entries for a sender
# HINT: start with soemthing like this:
# @app.route('/mail/sent/<sender>', ...)
if __name__ == '__main__':
app.run(port=5000, debug=True)