Better response bodies

This commit is contained in:
Anthony Wang 2022-05-23 22:21:57 -05:00
parent d598eb3f79
commit 4ac68b006e
Signed by: a
GPG key ID: BC96B00AEC5F2D76

20
api.py
View file

@ -12,8 +12,8 @@ class api(BaseHTTPRequestHandler):
def send(self, code, body):
"""Send HTTP response and body"""
print(code, body)
self.send_response(code)
self.send_response(200)
self.send_header('Content-Type', 'text/plain')
self.send_header('Content-Length', str(len(body)))
self.end_headers()
@ -22,13 +22,16 @@ class api(BaseHTTPRequestHandler):
def do_GET(self):
"""Handle GET requests"""
self.send(200, 'Hello')
self.send(200, 'Hey there, you\'ve reached the top secret exozyme api')
def do_POST(self):
"""Handle API POST requests"""
content_length = int(self.headers['Content-Length'])
try:
data = dict(parse_qsl(self.rfile.read(content_length).decode('utf-8')))
except:
self.send(400, 'Oops, that request doesn\'t look quite right')
# Print debug data
debug = data.copy()
@ -39,20 +42,17 @@ class api(BaseHTTPRequestHandler):
if self.path == '/api/join':
# New user
if data['code'] != code():
print('Incorrect code')
self.send(403, 'Incorrect code')
self.send(403, 'Nice try, but that secret code is totally wrong')
return
if not all(c.isdigit() or c.islower() for c in data['username']) or data['username'][0].isdigit():
print('Bad username')
self.send(403, 'Bad username')
self.send(403, 'I don\'t like that username')
return
# Add the user
adduser(data['username'], data['firstname'].capitalize(), data['lastname'].capitalize(),
data['email'], data['password'])
else:
print('Bad request')
self.send(400, 'Bad request')
self.send(200, 'Well I think it worked...')
return
self.send(200, 'It worked!')
self.send(501, 'We don\'t know how to do that yet')