Domanda

I'm writing a Twitter application and trying to use tweepy for Authorization. I'm getting the following error, and can't figure out why..

Could anyone please help me out? I will greatly appreciate it.

Traceback (most recent call last):
File "getconv.py", line 32, in <module>
auth=AppAuthHandler(consumer_token,consumer_secret)
File "getconv.py", line 25, in __init__
response=urllib2.urlopen(req,data)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 126, in urlopen
return _opener.open(url, data, timeout)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 400, in open
response = meth(req, response)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 513, in http_response
'http', request, response, code, msg, hdrs)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 432, in error
result = self._call_chain(*args)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 372, in _call_chain
result = func(*args)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 619, in http_error_302
return self.parent.open(new, timeout=req.timeout)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 400, in open
response = meth(req, response)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 513, in http_response
'http', request, response, code, msg, hdrs)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 438, in error
return self._call_chain(*args)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 372, in _call_chain
result = func(*args)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 521, in http_error_default
raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib2.HTTPError: HTTP Error 403: Forbidden

Following is my code

import urllib2
import time
import sys
import tweepy
import base64
import urllib
#import twitter

consumer_token='my consumer token'
consumer_secret='my consumer secret'
access_token='my access token'
access_secret='my access secret'

class AppAuthHandler(tweepy.auth.AuthHandler):
    TOKEN_URL='http://api.twitter.com/oauth2/token'

    def __init__(self,consumer_key,consumer_secret):
            token_credential=urllib.quote(consumer_key)+':'+urllib.quote(consumer_secret)
            credential=base64.b64encode(token_credential)
            value={'grant_type':'client_credentials'}
            data=urllib.urlencode(value)
            req=urllib2.Request(self.TOKEN_URL)
            req.add_header('Authorization','Basic'+credential)
            req.add_header('Content_Type','application/x-www-form-urlencoded;charset=UTF-8')
            response=urllib2.urlopen(req,data)
            json_response=json.loads(response.read())
            self._access_token=json_response['access_token']

    def apply_auth(self,url,method,headers,parameters):
            headers['Authorization']='Bearer'+self._access_token

auth=AppAuthHandler(consumer_token,consumer_secret)
oauth_api=tweepy.API(auth)
È stato utile?

Soluzione

The error has nothing to do with tweepy, it's from your custom AppAuthHandler:

>>> auth = AppAuthHandler(TWITTER_CONSUMER_KEY, TWITTER_CONSUMER_SECRET)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
    raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib2.HTTPError: HTTP Error 403: Forbidden

There are actually three errors in your code:

  • Link should use https instead of http
  • Name for Content-Type header uses dash instead of underscore
  • Authorization header has to hold a space between Basic and credentials, add it.

I provide your code with fixes included for reference (didn't improve, only fix):

class AppAuthHandler(tweepy.auth.AuthHandler):
    TOKEN_URL='https://api.twitter.com/oauth2/token'
    def __init__(self,consumer_key,consumer_secret):
        token_credential = '{}:{}'.format(*map(urllib.quote, [consumer_key, consumer_secret]))
        credential = base64.b64encode(token_credential)
        value = {'grant_type': 'client_credentials'}
        data = urllib.urlencode(value)
        req = urllib2.Request(self.TOKEN_URL)
        req.add_header('Authorization', 'Basic {}'.format(credential))
        req.add_header('Content-Type', 'application/x-www-form-urlencoded;charset=UTF-8')
        response=urllib2.urlopen(req, data)
        json_response=json.loads(response.read())
        self._access_token=json_response['access_token']
    def apply_auth(self,url,method,headers,parameters):
        headers['Authorization'] = 'Bearer {}'.format(self._access_token)

Demo:

>>> AppAuthHandler(TWITTER_CONSUMER_KEY, TWITTER_CONSUMER_SECRET)
<__main__.AppAuthHandler object at 0x11b7d10>
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top