Created
August 21, 2017 23:25
-
-
Save theseanything/b0be2760b321b66a69fab3395e1cf736 to your computer and use it in GitHub Desktop.
HTTP server for an in-memory database
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from http.server import HTTPServer, BaseHTTPRequestHandler, __version__ | |
HOST = '' | |
PORT = 8080 | |
class DatabaseHTTPRequestHandler(BaseHTTPRequestHandler): | |
"""Request handler for interacting with a in-memory database""" | |
database = {} | |
def do_GET(self): | |
"""Serve a GET request""" | |
path, parameters = self._parse_path(self.path) | |
if path == "/set": | |
self.database.update(parameters) | |
self._send_message('OK') # simple reply to say the entry was accepted | |
elif path == "/get": | |
key = parameters.get("key") | |
value = self.database.get(key, '') # maybe better default response for no key | |
self._send_message(value) | |
else: | |
self.send_error(400) | |
def _parse_path(self, path): | |
"""Parses a URI for the path and query""" | |
path = path.split('#',1)[0] # ignore fragments in the URI | |
path, _, query = path.partition("?") | |
parameters = {} | |
for param in query.split("&"): | |
key, delim, value = param.partition("=") | |
if key and delim: | |
parameters[key] = value | |
return path, parameters | |
def _send_message(self, body): | |
"""Send a full 200 HTTP response back with body as data""" | |
self.send_response(200) # send response line | |
self.send_header('Content-type','text/plain') # send headers | |
self.end_headers() | |
self.wfile.write(bytes(body, "utf8")) # send data - maybe shouldn't use utf8 | |
if __name__ == '__main__': | |
db_server = HTTPServer((HOST, PORT), DatabaseHTTPRequestHandler) | |
try: | |
db_server.serve_forever() | |
except KeyboardInterrupt: # make sure connection is closed on KeyboardInterrupt | |
pass | |
finally: | |
db_server.server_close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment