Last active
February 26, 2021 21:21
-
-
Save chbrandt/5e40f6779219eb2dbcf3f1b845599e52 to your computer and use it in GitHub Desktop.
Database Server exercise
This file contains 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, ThreadingHTTPServer, BaseHTTPRequestHandler | |
from urllib.parse import urlparse, parse_qs | |
# Dictionary-db storing user key-value pairs. | |
# | |
_db = {} | |
_database_file = '/tmp/dataserver.txt' | |
_dbfile = open(_database_file, 'a') | |
class Handler(BaseHTTPRequestHandler): | |
""" | |
GET handler | |
When the server receives a 'set?somekey=somevalue' GET request, store key and value in memory. | |
When it receives a 'get?key=somekey' GET request, return the value stored at somekey. | |
""" | |
def __init__(self, *args, **kwargs): | |
super(Handler, self).__init__(*args,**kwargs) | |
_dbfile_read = open(_database_file, 'r') | |
for line in _dbfile_read.readlines(): | |
k,v = line.strip().split(':') | |
# _db.update({bytes(k,'utf-8'):bytes(v,'utf-8')}) | |
_db.update({k:v}) | |
print('DB***:',repr(k),repr(v)) | |
print('DB***:',type(k),type(v)) | |
# and then you open it up for writing/appending | |
#_dbfile = open(_database_file, 'a') | |
# def __del__(self): | |
# self._dbfile.close() | |
def _get(self): | |
o = urlparse(self.path) | |
pairs = parse_qs(o.query) | |
if o.path == '/set': | |
pairs_first = {str(k):str(v[0]) for k,v in pairs.items()} | |
for k,v in pairs_first.items(): | |
print('SET***:',repr(k),repr(v)) | |
print('SET***:',type(k),type(v)) | |
_db.update(pairs_first) | |
for k,v in pairs_first.items(): | |
print('{k}:{v}'.format(k=k,v=v), file=_dbfile) | |
_dbfile.flush() | |
return b'All set!' | |
elif o.path == '/get': | |
for k,v in _db.items(): | |
print('GET***:',repr(k),repr(v)) | |
print('GET***:',type(k),type(v)) | |
pairs_vals = {k:_db[k] for p,vs in pairs.items() if p == 'key' | |
for k in vs if k in _db} | |
ans = '\n'.join([F'{k}:{v}' for k,v in pairs_vals.items()]) | |
return bytes(ans, 'utf-8') | |
else: | |
return b'Oops: command not found.' | |
def do_GET(self): | |
ans = self._get() | |
if ans: | |
print(ans) | |
self.send_response(200) | |
self.end_headers() | |
self.wfile.write(ans) | |
if __name__ == '__main__': | |
host = '' | |
port = 4000 | |
server_address = (host, port) | |
httpd = ThreadingHTTPServer(server_address, Handler) | |
# httpd = HTTPServer(server_address, Handler) | |
print(F"Server running at localhost:{port}...") | |
httpd.serve_forever() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment