Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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)
- # What happens @ / or the main page
- class MainHandler(tornado.web.RequestHandler):
- 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(tornado.web.RequestHandler):
- 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(tornado.web.RequestHandler):
- 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="randomP@ss123").create_user()
- me = UserObject(name="Jasmit", username="jt123", password="randomP@ss123").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()
Add Comment
Please, Sign In to add comment