Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Twitter authentication with Tornado
class TwitterHandler(tornado.web.RequestHandler,
tornado.auth.TwitterMixin):
"""Handling Twitter authentication at URL http://www.yoursite.com/twitter"""
@tornado.web.asynchronous
def get(self):
if self.get_argument("oauth_token", None):
user = self.get_authenticated_user(self.async_callback(self._on_auth))
return
self.authenticate_redirect()
def _on_auth(self, user):
if not user:
raise tornado.web.HTTPError(500, "Twitter auth failed")
# safe the user information in secure cookie
self.set_secure_cookie('screen_name', user['access_token']['screen_name'])
self.set_secure_cookie('user_id', user['access_token']['user_id'])
self.set_secure_cookie('access_token_key', user['access_token']['key'])
self.set_secure_cookie('access_token_secret', user['access_token']['secret'])
# you need to complete the request by either redirecting to success page
self.redirect('/success')
# or by writing the response in the callback method
# self.write("@" + user['access_token']['screen_name'] + " is succesfully authenticated with Twitter")
# self.finish()
class SuccessHandler(tornado.web.RequestHandler):
def get(self):
twitter_user = self.get_secure_cookie('screen_name')
self.write("@" + twitter_user + " is succesfully authenticated with Twitter")
self.finish()
settings = {
'cookie_secret'="_GENERATE_YOUR_OWN_RANDOM_VALUE_HERE_"
'twitter_consumer_key': '_YOUR_APPS_CONSUMER_KEY_',
'twitter_consumer_secret': '_YOUR_APPS_CONSUMER_SECRET_',
}
application = tornado.web.Application([
(r"/", TwitterHandler),
(r"/success", SuccessHandler)
], **settings)
if __name__ == "__main__":
application.listen(8888)
tornado.ioloop.IOLoop.instance().start()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment