Example: Sign in With Twitter

Let’s walk through an example that uses the Twitter API to authenticate a user. This application will redirect a nonlogged-in user to Twitter’s authorization page, which prompts the user for his screenname and password. Twitter then redirects the user to a URL you specify in Twitter’s application settings page.

First, you must register a new application on Twitter. The Twitter Developers site has a “Create an app” link where you can get started, if you don’t have an app already. Once you create your Twitter application, you will be assigned an access token and a secret that identifies your application to Twitter. You’ll need to fill in those values in the appropriate places in the source code we show in this section.

Now let’s take a look at the code in Example 7-1.

Example 7-1. View Twitter timeline: twitter.py

import tornado.web import tornado.httpserver import tornado.auth import tornado.ioloop class TwitterHandler(tornado.web.RequestHandler, tornado.auth.TwitterMixin): @tornado.web.asynchronous def get(self): oAuthToken = self.get_secure_cookie('oauth_token') oAuthSecret = self.get_secure_cookie('oauth_secret') userID = self.get_secure_cookie('user_id') if self.get_argument('oauth_token', None): self.get_authenticated_user(self.async_callback(self._twitter_on_auth)) return elif oAuthToken and oAuthSecret: accessToken = { 'key': oAuthToken, 'secret': oAuthSecret } self.twitter_request('/users/show', access_token=accessToken, user_id=userID, callback=self.async_callback(self._twitter_on_user) ...

Get Introduction to Tornado 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.