Last active
October 24, 2018 03:56
-
-
Save jtarang/53d95eaa08c3f3d361b38c552447888d to your computer and use it in GitHub Desktop.
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
import tornado.ioloop | |
import tornado.web | |
import json | |
# Creates a user | |
class UserObject: | |
def __init__(self, name, username, password): | |
self.user = username | |
self.passwd = password | |
self.name = name | |
# instead of creating a big json object | |
# create a class and it will make it for you | |
# repetitve task | |
def create_user(self): | |
return dict(username=self.user, password=self.passwd, name=self.name) | |
# Need this for cross origin stuff | |
class BaseHandler(tornado.web.RequestHandler): | |
def set_default_headers(self): | |
print("setting headers!!!") | |
self.set_header("Access-Control-Allow-Origin", "*") | |
self.set_header("Access-Control-Allow-Headers", "x-requested-with") | |
self.set_header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS') | |
# default action if no get is there for a route. | |
def get(self): | |
self.write('some get') | |
# What happens @ / or the main page | |
class MainHandler(BaseHandler): | |
def get(self): | |
self.write("\n\t/users : get all users\n\t /login: login") | |
# dumps all the users this is a `GET` | |
class GetUsers(BaseHandler): | |
def get(self): | |
self.write(json.dumps(list_of_all_users)) | |
# validates from hard coded users | |
# if username and password are correct it returns the userinfo | |
class Login(BaseHandler): | |
def post(self): | |
args = json.loads(self.request.body) | |
try: | |
for user in list_of_all_users['users']: | |
if args['user'] == user['username'] and args['passwd'] == user['password']: | |
self.write(user) | |
except: | |
self.write(dict(error="user not found, please check your credentials")) | |
def make_app(): | |
# tie the functions with the route | |
return tornado.web.Application([ | |
(r"/", MainHandler), | |
(r"/users", GetUsers), | |
(r"/login", Login), | |
]) | |
if __name__ == "__main__": | |
# create users start | |
big_bro = UserObject(name="Paramjit", username="pj123", password="123").create_user() | |
me = UserObject(name="Jasmit", username="jt123", password="123").create_user() | |
# creat users end | |
list_of_all_users = dict(users=[big_bro, me]) # group users in a json object | |
app = make_app() # start the server | |
app.listen(8888) # uses port 8888 | |
# tries to start the server | |
try: | |
tornado.ioloop.IOLoop.current().start() | |
# if something is wrong or ctrl + c is pressed it stops | |
except: | |
tornado.ioloop.IOLoop.current().stop() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment