Logging In
The first thing we’ll need to add to this script is the ability for users to sign in. This won’t be a complicated login process; it will only require users to select a username in order to access the system. Using Tornado’s authentication functionality, it would be fairly easy to implement a much more robust login scheme, but that’s overkill for this example.
On the Server Side
To accommodate users logging into the chat application, the Python
script is going to need to accept login requests for the form we created
before. To do that, we’ll need to expand
the list of URL handlers from the main application class. In the
chat-server.py file, locate the
Application
class and make the following highlighted
change:
class Application(tornado.web.Application): def __init__(self): # setup the URL handlers handlers = [ (r"/", MainHandler),(r"/login/?", LoginHandler),
(r"/updates/?", UpdateHandler),
]
This addition tells Tornado to accept requests for
/login
and direct them to a class called
LoginHandler
. That class is illustrated next; add it
to the chat-server.py file:
class LoginHandler(BaseHandler): def post(self): # generate a unique ID for each user user_id = str(uuid.uuid4()) # get the user_name submitted from the form user_name = self.get_argument('username') # Add this user to the chat class self.chat.add_user(user_id, user_name) # We're done, notify the client. self.finish(dict(user_id=user_id, user_name=user_name, users=self.chat.users))
This login handler class just does ...
Get Building the Realtime User Experience now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.