Skip to content

Instantly share code, notes, and snippets.

@chbrandt
Last active February 26, 2021 21:21
Show Gist options
  • Save chbrandt/5e40f6779219eb2dbcf3f1b845599e52 to your computer and use it in GitHub Desktop.
Save chbrandt/5e40f6779219eb2dbcf3f1b845599e52 to your computer and use it in GitHub Desktop.
Database Server exercise
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