我无法检索环境变量。
我尝试了Tweepy
文档中的示例代码段,没有环境变量,并且该代码段应能正常工作。我直接在代码中定义了所需的变量。
然后我为consumer_key, consumer_secret, access_token and access_token_secret
定义了 4个环境变量,但此方法不再起作用。让我感到奇怪的是,我可以使用print(os.environ['TWITTER_CONSUMER_KEY'])
访问环境变量,并且输出正确。
键中没有任何错字。我仔细检查了。
此代码有效:
import tweepy
consumer_key = 'xyz'
consumer_secret = 'xyz'
access_token = 'xyz'
access_token_secret = 'xyz'
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)
public_tweets = api.home_timeline()
for tweet in public_tweets:
print(tweet.text)
此代码无效:
import os
import tweepy
consumer_key = os.environ['TWITTER_CONSUMER_KEY']
consumer_secret = os.environ['TWITTER_CONSUMER_SECRET']
access_token = os.environ['TWITTER_ACCESS_TOKEN']
access_token_secret = os.environ['TWITTER_ACCESS_SECRET']
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)
public_tweets = api.home_timeline()
for tweet in public_tweets:
print(tweet.text)
我收到以下错误消息:
Traceback (most recent call last):
File "[...]/testing.py", line 28, in <module>
public_tweets = api.home_timeline()
File "[...]venv\lib\site-packages\tweepy\binder.py", line 250, in _call
return method.execute()
File "[...]\venv\lib\site-packages\tweepy\binder.py", line 234, in execute
raise TweepError(error_msg, resp, api_code=api_error_code) tweepy.error.TweepError: [{'code': 32, 'message': 'Could not authenticate you.'}]
答案 0 :(得分:-1)
您需要上传dotenv库
from dotenv import load_dotenv
load_dotenv()