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 ofhttp
- Name for
Content-Type
header uses dash instead of underscore Authorization
header has to hold a space betweenBasic
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>