Pylons and Twitter Based Authorization

Implementing Twitter authorization in Pylons is easy as butter, I will show you how to do it in the next steps.

Download python-twitter and install it

  python build
  python install

Download and install dependencies

Now you’re almost there. There’s a file called that you need to call in order to obtain the Twitter session secret_token, but I decided to create a class based from that file instead. Save this class on your project lib folder as

import os
import sys
# parse_qsl moved to urlparse module in v2.6
  from urlparse import parse_qsl
  from cgi import parse_qsl
import oauth2 as oauth
SIGNIN_URL        = ''
class GenerateToken(object):
  def __init__(self,consumer_key=None,consumer_secret=None):
    if consumer_key is None or consumer_secret is None:
      raise TokenError('please add a consumer key and secret')
      signature_method_hmac_sha1 = oauth.SignatureMethod_HMAC_SHA1()
      self.oauth_consumer             = oauth.Consumer(key=consumer_key, secret=consumer_secret)
      self.oauth_client               = oauth.Client(self.oauth_consumer)
  def getrequestTokenURL(self):
    resp, content = self.oauth_client.request(REQUEST_TOKEN_URL, 'GET')
    if resp['status'] != '200':
      raise TokenError('Invalid response from Twitter')
      request_token = dict(parse_qsl(content))
      pieces = {
        'url' : "%s?oauth_token=%s" % (AUTHORIZATION_URL, request_token['oauth_token']),
        'token_secret': request_token['oauth_token_secret']
      return pieces
  def authRequest(self,oauth_token=None,oauth_token_secret=None,oauth_verifier=None):
      token = oauth.Token(oauth_token,oauth_token_secret)
      oauth_client  = oauth.Client(self.oauth_consumer, token)
      resp, content = oauth_client.request(ACCESS_TOKEN_URL, method='POST', body='oauth_verifier=%s' % oauth_verifier)
      access_token  = dict(parse_qsl(content))
      if resp['status'] != '200':
        raise TokenError('The request for a Token %s did not succeed: %s' % (access_token,resp['status']) )
        auth = {
          'access_token' : access_token['oauth_token'],
          'access_token_secret' : access_token['oauth_token_secret'],
        return auth
class TokenError(Exception):
  '''Base class for Token errors'''
  def message(self):
    '''Returns the first argument used to construct this error.'''
    return self.args[0]


create a controller in this case I’ll create an account controller

 paster controller account
import twitter
import PRJNAME.lib.twittertoken as twittertoken
def twitter_auth(self):
    token = twittertoken.GenerateToken(consumer_key=config['twitter.key'], consumer_secret=config['twitter.secret'])
    request_token = token.getrequestTokenURL()
    #save the token secret it will be used to generate the user's access_token and and access_secret
    session['token_secret'] = request_token['token_secret']
    # redirect to twitter screen
    return redirect(url(request_token['url']))
def twitter_preferences(self):
   params = request.params
   twittertoken.GenerateToken(consumer_key=config['twitter.key'], consumer_secret=config['twitter.secret'])
  auth = twittertoken.authRequest(oauth_token=params.get('oauth_token'),oauth_token_secret=session.get('token_secret'),oauth_verifier=params.get('oauth_verifier'))
  if auth['access_token'] and auth['access_token_secret']:
  #save to db or get user friend list
  for u in api.GetFriends():

I hope it helps to someone looking to implement Twitter on their Pylons projects.


Pylons and Facebook based Authorization with OAuth 2.0

Authorizing a user using Facebook OAuth 2.0 based login it’s pretty straighfoard. This is for the person who asked a question on I hope it helps.

Add the apikey, appid and secret of my Facebook app to the development.ini file

facebook.apikey = 42bc5a4051b274ede5cb73a6cd6fad56
facebook.secret = a355e66e8c0293390896a170f9d5r4c3
facebook.appid = 20894420580890

Configure my model/ file:

from PRJNAME.model.meta import Session, Base
from sqlalchemy import Column
from sqlalchemy import Integer
from sqlalchemy import Unicode
from sqlalchemy import Table
from sqlalchemy import Text
from sqlalchemy import Unicode
from sqlalchemy import BigInteger
from sqlalchemy import TIMESTAMP
from sqlalchemy import ForeignKey,ForeignKeyConstraint
from sqlalchemy.orm import mapper
import datetime
def init_model(engine):
    """Call me before using any of the tables or classes in the model"""
def now():
social_user = Table('social_user', Base.metadata,
    Column('id', Integer, primary_key=True),
    Column('oauth_provider', Text(), nullable=False),
    Column('oauth_id', Text() , nullable=False),
    Column('username', Unicode(50), nullable=False),
    Column('access_token', Unicode(200)),
    Column('created', TIMESTAMP(timezone=True), default=now()),
  class Social(object):

Download the Facebook Python-SDK

And save it on your project lib directory

Create a controller named account

~$ paster controller account

Add a view named login and render a login button

I’ll use as the url to start the authorization process

 import PRJNAME.lib.facebook as facebook
 import simplejson
 from pylons import config
 class AccountController(BaseController):
   def login(self):
     params = {
       'scope' : 'offline_access,publish_stream,email', #permissions needed by the app
       'redirect_uri' : 'http://'+request.environ['HTTP_HOST']+'/account/auth'
     keys = params.keys()[:]
     q_str = unicode()
     for name in keys:
       q_str+= ("&%s=%s" % (name,params[name]))
     c.login_url = '' + q_str
     return render('/website/login.html')


<h1>Login with Facebook</h1>
<p><a href="${c.login_url}"><img src="/images/fblogin.png" alt="login with Facebook" /></a></p>

Add a function on

This function will create our access_token from our code request params

  import urllib
  import json
  def getAccessTokenFromCode(applicationId, applicationSecret, code,redirect_uri):
    q_str = unicode()
    params = {
    keys = params.keys()[:]
    for name in keys:
      q_str+= ("&%s=%s" % (name, params[name]))
    url = ''+ q_str
    response = urllib.urlopen(url).read()
    result = response.split('=')[-1]
    if result:
      return result

Create an auth view on account controller

I do this because in the link button there is an argument called redirect_uri that points to

from PRJNAME.lib.helpers import getAccessTokenFromCode
from pylons import config
def auth(self):
if request.params.has_key('code'):
      access_token = getAccessTokenFromCode(
      graph = facebook.GraphAPI(access_token)
      #grab the user data
      fbdata = graph.get_object("me") 
      #query the db to check if user is already authorized
      q = Session.query(model.Social)
      user = q.filter_by(oauth_id=fbdata['id']).first()
      if user:
       # you can redirect to a dashboard
       return 'already in db and authorized'
      #insert user data to db
      fb = model.Social()
      fb.oauth_provider = 'Facebook'
      fb.oauth_id = fbdata['id']
      fb.username = fbdata['name']
      fb.access_token = access_token
      # redirect to dashboard page

And that’s pretty much it.