Skip to content

Instantly share code, notes, and snippets.

@wambu-i
Last active December 18, 2018 23:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wambu-i/1a29d0ef6539480b84f5e3ce09839c78 to your computer and use it in GitHub Desktop.
Save wambu-i/1a29d0ef6539480b84f5e3ce09839c78 to your computer and use it in GitHub Desktop.
Database server.
import requests
class ServerRequest:
def __init__(self, host, port):
self.address = '{}:{}'.format(host, port)
def _get(self, key):
request = '{0}/get?key={1}'.format(self.address, key)
response = requests.get(request)
if response.status_code == 200:
print(response.text)
elif response.status_code == 404:
print("Value for specified key does not exist!")
else:
print("Request could not be successfully fulfilled")
def _post(self, key, value):
request = '{0}/set?{1}={2}'.format(self.address, key, value)
response = requests.post(request)
if response.status_code == 200:
print("Key-Value pair successfully stored!")
else:
print("Key-Value pair was not successfully stored!")
if __name__ == "__main__":
client = ServerRequest('http://localhost', '4000')
client._post("One", "Cow")
client._post("Two", "Dog")
client._get("Two")
client._get("Ten")
from http.server import HTTPServer, BaseHTTPRequestHandler
from urllib.parse import urlparse, parse_qs
pairs = []
class KeyPairServer(BaseHTTPRequestHandler):
def set_headers(self, code):
self.send_response(code)
self.send_header("Content-Type", "application/json")
self.end_headers()
def do_GET(self):
params = parse_qs(self.path[5:])
requested = ''.join(params["key"])
value = self.get_value(requested)
if value is not None:
value = ''.join(value)
self.set_headers(200)
self.wfile.write(value.encode("utf-8"))
else:
self.set_headers(404)
def get_value(self, requested):
value = None
for i in range(len(pairs)):
for key in pairs[i]:
if key == requested:
value = pairs[i][key]
return value
def do_POST(self):
path = dict(parse_qs(self.path[5:]))
pairs.append(path)
self.set_headers(200)
def main():
server = HTTPServer(('localhost', 4000), KeyPairServer)
server.serve_forever()
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment