tweepy错误的身份验证数据

时间:2017-10-06 08:59:43

标签: python python-3.x twitter tweepy

我试图通过tweepy访问twitter api。我收到tweepy.error.TweepError: [{'code': 215, 'message': 'Bad Authentication data.'}]错误。

我的API访问权限在twitter_client.py

中描述
import os
import sys
from tweepy import API
from tweepy import OAuthHandler

def get_twitter_auth():
    """Setup twitter authentication
    Return: tweepy.OAuthHandler object
    """

    try:
        consumer_key = os.environ['TWITTER_CONSUMER_KEY']
        consumer_secret = os.environ['TWITTER_CONSUMER_SECRET']
        access_token = os.environ['TWITTER_ACCESS_TOKEN']
        access_secret = os.environ['TWITTER_ACCESS_SECRET']
    except KeyError:
        sys.stderr.write("TWITTER_* environment variable not set\n")
        sys.exit(1)

    auth = OAuthHandler(consumer_key, consumer_secret)
    auth.set_access_token(access_token, access_secret)

    return auth

def get_twitter_client():
    """Setup twitter api client
    Return: tweepy.API object
    """
    auth = get_twitter_auth()
    client = API(auth)

    return client

然后我尝试获取我的最后4条推文:

from tweepy import Cursor
from twitter_client import get_twitter_client

if __name__ == '__main__':
    client = get_twitter_client()

    for status in Cursor(client.home_timeline()).items(4):
        print(status.text)

得到那个错误。我如何解决它?

我正在使用python 3.6并且我通过pip whithout指定了一个版本安装了tweepy,因此它应该是tweepy的最后一个版本。

Upd:我发现问题出在环境变量中。不知何故,twitter api无法得到它。但是,当我只是print(consumer_key, consumer_secret, access_token, access_secret)时,一切都在它的位置

1 个答案:

答案 0 :(得分:0)

import tweepy

以这种方式导入可提高代码可读性,尤其是在使用时。 例如tweepy.API()

client.home_timeline()

home_timeline之后的括号不应该在那里。

应该是

for status in Cursor(client.home_timeline).items(4):
    print(status.text)

import tweepy 

auth = tweepy.OAuthHandler(<consumer_key>, <consumer_secret>)
auth.set_access_token(<access_token>, <access_secret>)

client = tweepy.API(auth)

for status in tweepy.Cursor(client.user_timeline).items(200):
    process_status(status.text)
相关问题