Search code examples
pythonpython-2.7oauthweb-scrapingtwitter-oauth

Using Oauth library in python


I am running a twitter api in python using oauth library. I have included the code below. When I run the code "twtest.py", I get the error `'module' object has no attribute 'OAuthConsumer'.

1.twtest.py

  import urllib
    from twurl import augment

    print '* Calling Twitter...'
    url = augment('https://api.twitter.com/1.1/statuses/user_timeline.json',
            {'screen_name': 'saurabhpathak20', 'count': '2'} )
    print url
    connection = urllib.urlopen(url)
    data = connection.read()
    print data
    headers = connection.info().dict
    print headers

2.twurl.py

import urllib
import oauth
import hidden

def augment(url, parameters) :
    secrets = hidden.oauth()
    consumer = oauth.OAuthConsumer(secrets['consumer_key'], secrets['consumer_secret'])
    token = oauth.OAuthToken(secrets['token_key'],secrets['token_secret'])

    oauth_request = oauth.OAuthRequest.from_consumer_and_token(consumer, 
        token=token, http_method='GET', http_url=url, parameters=parameters)
    oauth_request.sign_request(oauth.OAuthSignatureMethod_HMAC_SHA1(), consumer, token)
    return oauth_request.to_url()


def test_me() :
    print '* Calling Twitter...'
    url = augment('https://api.twitter.com/1.1/statuses/user_timeline.json',
        {'screen_name': 'saurabhpathak20', 'count': '2'} )
    print url
    connection = urllib.urlopen(url)
    data = connection.read()
    print data
    headers = connection.info().dict
    print headers

3.hidden.py

def oauth() :
    return { "consumer_key" : "pj......U8fFRyjV",
        "consumer_secret" : "zty3njhO4IRl........ELh1YC1j1rX",
        "token_key" : "515167047-xaRfSm7.......wBBOrjNd61anI55D",
        "token_secret" : "  y7ZCBDf6d..........x1eJV8mHRnL8hh" }

Kindly help me to understand what is wrong in the code. Thanks.


Solution

  • You need to import oauth from oauth instead of import oauth

    >>> from oauth import oauth
    >>> oauth.OAuthConsumer
    <class 'oauth.oauth.OAuthConsumer'>