Guest User

Untitled

a guest
Oct 22nd, 2018
132
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.04 KB | None | 0 0
  1. import tornado.ioloop
  2. import tornado.web
  3. import json
  4.  
  5. # Creates a user
  6. class UserObject:
  7.  
  8. def __init__(self, name, username, password):
  9. self.user = username
  10. self.passwd = password
  11. self.name = name
  12.  
  13. # instead of creating a big json object
  14. # create a class and it will make it for you
  15. # repetitve task
  16. def create_user(self):
  17. return dict(username=self.user, password=self.passwd, name=self.name)
  18.  
  19. # What happens @ / or the main page
  20. class MainHandler(tornado.web.RequestHandler):
  21. def get(self):
  22. self.write("\n\t/users : get all users\n\t /login: login")
  23.  
  24. # dumps all the users this is a `GET`
  25. class GetUsers(tornado.web.RequestHandler):
  26. def get(self):
  27. self.write(json.dumps(list_of_all_users))
  28.  
  29. # validates from hard coded users
  30. # if username and password are correct it returns the userinfo
  31. class Login(tornado.web.RequestHandler):
  32. def post(self):
  33. args = json.loads(self.request.body)
  34. try:
  35. for user in list_of_all_users['users']:
  36. if args['user'] == user['username'] and args['passwd'] == user['password']:
  37. self.write(user)
  38. except:
  39. self.write(dict(error="user not found, please check your credentials"))
  40.  
  41.  
  42. def make_app():
  43. # tie the functions with the route
  44. return tornado.web.Application([
  45. (r"/", MainHandler),
  46. (r"/users", GetUsers),
  47. (r"/login", Login),
  48. ])
  49.  
  50. if __name__ == "__main__":
  51. # create users start
  52. big_bro = UserObject(name="Paramjit", username="pj123", password="randomP@ss123").create_user()
  53. me = UserObject(name="Jasmit", username="jt123", password="randomP@ss123").create_user()
  54. # creat users end
  55. list_of_all_users = dict(users=[big_bro, me]) # group users in a json object
  56. app = make_app() # start the server
  57. app.listen(8888) # uses port 8888
  58. # tries to start the server
  59. try:
  60. tornado.ioloop.IOLoop.current().start()
  61. # if something is wrong or ctrl + c is pressed it stops
  62. except:
  63. tornado.ioloop.IOLoop.current().stop()
Add Comment
Please, Sign In to add comment