-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrequest_handler.py
More file actions
213 lines (179 loc) · 7.4 KB
/
request_handler.py
File metadata and controls
213 lines (179 loc) · 7.4 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
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
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
import json
from http.server import BaseHTTPRequestHandler, HTTPServer
from views import get_all_posts, get_single_post, create_post, update_post, delete_post
from views import create_category, update_category, create_subscription, delete_subscription, update_subscription
from views import create_user, login_user, get_single_user, get_all_users, update_user, delete_user
from views import get_single_comment,get_all_comments,create_comment,delete_comment,update_comment
from views import get_single_posttags,get_all_posttags,create_posttag,delete_posttag,update_posttag
from views import get_all_categories,get_single_category,delete_category
from views import get_all_subscriptions, get_single_subscription, get_subscriptions_by_author
from views import get_all_tags,get_single_tag,update_tag,delete_tag,create_tag
class HandleRequests(BaseHTTPRequestHandler):
"""Handles the requests to this server"""
def parse_url(self):
"""Parse the url into the resource and id"""
path_params = self.path.split('/')
resource = path_params[1]
if '?' in resource:
param = resource.split('?')[1]
resource = resource.split('?')[0]
pair = param.split('=')
key = pair[0]
value = pair[1]
return (resource, key, value)
else:
id = None
try:
id = int(path_params[2])
except (IndexError, ValueError):
pass
return (resource, id)
def do_GET(self):
"""Handles GET request to the server"""
self._set_headers(200)
response = {}
# If the path does not include a query parameter, continue with the original if block
if '?' not in self.path:
( resource, id ) = self.parse_url()
# It's an if..else statement
if resource == "Comments":
if id is not None:
response = get_single_comment(id)
else:
response = get_all_comments()
if resource == "PostTags":
if id is not None:
response= get_single_posttags(id)
else:
response= get_all_posttags()
if resource == "Categories":
if id is not None:
response = get_single_category(id)
else:
response = get_all_categories()
if resource == "Subscriptions":
if id is not None:
response= get_single_subscription(id)
else:
response= get_all_subscriptions()
if resource == "Posts":
if id is not None:
response= get_single_post(id)
else:
response= get_all_posts()
if resource == "Users":
if id is not None:
response = get_single_user(id)
else:
response = get_all_users()
if resource == "Tags":
if id is not None:
response = get_single_tag(id)
else:
response = get_all_tags()
else:
(resource, query, value) = self.parse_url()
if resource == "Subscriptions" and query=="author_id":
response = get_subscriptions_by_author(value)
self.wfile.write(json.dumps(response).encode())
def _set_headers(self, status):
"""Sets the status code, Content-Type and Access-Control-Allow-Origin
headers on the response
Args:
status (number): the status code to return to the front end
"""
self.send_response(status)
self.send_header('Content-type', 'application/json')
self.send_header('Access-Control-Allow-Origin', '*')
self.end_headers()
def do_OPTIONS(self):
"""Sets the OPTIONS headers
"""
self.send_response(200)
self.send_header('Access-Control-Allow-Origin', '*')
self.send_header('Access-Control-Allow-Methods',
'GET, POST, PUT, DELETE')
self.send_header('Access-Control-Allow-Headers',
'X-Requested-With, Content-Type, Accept')
self.end_headers()
def do_POST(self):
"""Make a post request to the server"""
self._set_headers(201)
content_len = int(self.headers.get('content-length', 0))
post_body = json.loads(self.rfile.read(content_len))
response = ''
resource, _ = self.parse_url()
if resource == 'login':
response = login_user(post_body)
if resource == 'register':
response = create_user(post_body)
if resource == 'Posts':
response = create_post(post_body)
if resource == 'Comments':
response = create_comment(post_body)
if resource == 'PostTags':
response = create_posttag(post_body)
if resource == 'Tags':
response = create_tag(post_body)
if resource == 'Categories':
response = create_category(post_body)
if resource == 'Subscriptions':
response = create_subscription(post_body)
self.wfile.write(json.dumps(response).encode())
def do_PUT(self):
"""Handles PUT requests to the server"""
content_len = int(self.headers.get('content-length', 0))
post_body = self.rfile.read(content_len)
post_body = json.loads(post_body)
# Parse the URL
(resource, id) = self.parse_url()
# set default value of success
success = False
if resource == 'Posts':
success = update_post(id, post_body)
if resource == 'Categories':
success = update_category(id, post_body)
if resource == 'Subscriptions':
success = update_subscription(id, post_body)
if resource == 'Comments':
success = update_comment(id, post_body)
if resource == 'PostTags':
success = update_posttag(id, post_body)
if resource == 'Tags':
success = update_tag(id, post_body)
if resource == 'Users':
success = update_user(id, post_body)
print(success)
if success:
self._set_headers(204)
else:
self._set_headers(404)
self.wfile.write(json.dumps(success).encode())
#self.wfile.write("".encode())
def do_DELETE(self):
self._set_headers(204)
# Parse the URL
(resource, id) = self.parse_url()
# Delete a single animal from the list
if resource == "Categories":
delete_category(id)
if resource == "Subscriptions":
delete_subscription(id)
if resource == "Comments":
delete_comment(id)
if resource == "Posts":
delete_post(id)
if resource == "PostTags":
delete_posttag(id)
if resource == "Tags":
delete_tag(id)
if resource == 'Users':
delete_user(id)
def main():
"""Starts the server on port 8088 using the HandleRequests class
"""
host = ''
port = 8088
HTTPServer((host, port), HandleRequests).serve_forever()
if __name__ == "__main__":
main()