【问题标题】:How can I read the API authentication data from a file using Python?如何使用 Python 从文件中读取 API 身份验证数据?
【发布时间】:2014-08-15 01:30:34
【问题描述】:

从文件中读取我的 API 密钥时,我遇到了“错误的身份验证”错误:

#!/usr/local/bin/python
import tweepy

#open a file called "keys" with keys and tokens for Twitter separated by newlines
keyFile = open('keys', 'r')
consumer_key = keyFile.readline()
consumer_secret = keyFile.readline()
access_token = keyFile.readline()
access_token_secret = keyFile.readline()
keyFile.close()
print "consumer key: " + consumer_key
print "consumer secret: " + consumer_secret
print "access token: " + access_token
print "access token secret: " + access_token_secret

auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)

如果我手动设置我的密钥,比如consumer_key = "xxx",它可以正常工作。从文件读取时为什么不起作用的任何提示?谢谢。

【问题讨论】:

    标签: python twitter-oauth tweepy


    【解决方案1】:

    所以事实证明 Python 也在读取换行符。解决方案是用 rstrip() 去除隐藏字符:

    consumer_key = keyFile.readline().rstrip()

    【讨论】:

    • 是的,我也遇到了同样的问题。我试过consumer_key = f.readline()[:-1],但这并没有成功。谢谢!
    【解决方案2】:

    keys.txt 文件有 4 行,包括 consumer_keyconsumer_secretaccess_tokenaccess_token_secret,每行分别位于一行,因此我们首先使用 readlines 方法读取 keys.txt 文件中的所有行。我们需要使用.rstrip() 来从每个字符串(或其他可能不需要的字符)的末尾删除不需要的\n。将这些信息保存在keys.txt 文件中并在将您的项目推送到GitHub 时将keys.txt 文件的名称添加到.gitignore 是一个很好的做法,这样当您将代码推送到时其他人就不会破解您的帐户GitHub.

    keys_file = open("keys.txt")
    lines = keys_file.readlines()
    consumer_key = lines[0].rstrip()
    consumer_secret = lines[1].rstrip()
    access_token = lines[2].rstrip()
    access_token_secret = lines[3].rstrip()
    

    【讨论】:

    • 最好是添加一些澄清而不只是代码sn-p,以便更好地理解。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-22
    • 2021-06-02
    • 1970-01-01
    相关资源
    最近更新 更多