Created
May 23, 2018 19:35
-
-
Save bosswissam/7d7d58ee871be0d66573aeeeae1d5c12 to your computer and use it in GitHub Desktop.
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
import json | |
import tornado.ioloop | |
import tornado.web | |
DB = dict() | |
class BaseHandler(tornado.web.RequestHandler): | |
def validate_input(self): | |
if not isinstance(self.json_args.get('key'), str): | |
self.write(dict(success=False, reason="key must be a string")) | |
def prepare(self): | |
if self.request.headers.get("Content-Type", "") == "application/json": | |
try: | |
self.json_args = json.loads(self.request.body) | |
except json.decoder.JSONDecodeError as e: | |
# TODO return error message | |
self.json_args = None | |
else: | |
self.validate_input() | |
else: | |
self.json_args = None | |
class ResourceHandler(BaseHandler): | |
def get(self, key): | |
self.write(json.dumps(DB[key])) | |
class MainHandler(BaseHandler): | |
def get(self): | |
self.write(json.dumps(DB)) | |
def post(self): | |
key = self.json_args.get('key') | |
value = self.json_args.get('value') | |
if key not in DB: | |
DB[key] = value | |
success = True | |
else: | |
success = False | |
self.write(json.dumps(dict(success=success))) | |
def put(self): | |
key = self.json_args.get('key') | |
value = self.json_args.get('value') | |
if key in DB: | |
DB[key] = value | |
success = True | |
else: | |
success = False | |
self.write(json.dumps(dict(success=success))) | |
def delete(self): | |
key = self.json_args.get('key') | |
if key in DB: | |
del DB[key] | |
success = True | |
else: | |
success = False | |
self.write(json.dumps(dict(success=success))) | |
def make_app(): | |
print("starting server") | |
return tornado.web.Application([ | |
(r"/", MainHandler), | |
(r"/([a-zA-Z0-9]+)", ResourceHandler), | |
], | |
debug=True) | |
if __name__ == "__main__": | |
app = make_app() | |
app.listen(8888) | |
tornado.ioloop.IOLoop.current().start() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
you'll need to install tornado - guide here: http://www.tornadoweb.org/en/stable/guide/structure.html