所以我尝试使用Flask框架进行练习项目的tweepy auth ..但是当我尝试使用Tweepy和Flask使用OAuth时,我得到302返回说明无法获取访问令牌..请帮助..下面的代码和错误消息..
from flask import Flask, redirect, url_for, session, request, render_template, flash
import tweepy
import flask
app = Flask(__name__)
app.config.from_object('config')
oauth = OAuth()
consumer_key = app.config["CONSUMER_ID"]
consumer_secret = app.config["CONSUMER_SECRET"]
access_token_key = app.config["ACCESS_KEY"]
access_token_secret = app.config["ACCESS_SECRET"]
callback_url = 'http://localhost:5000/verify'
session = dict()
db = dict()
@app.route('/')
def send_token():
redirect_url = ""
auth = tweepy.OAuthHandler(consumer_key, consumer_secret, callback_url)
try:
#get the request tokens
redirect_url= auth.get_authorization_url()
session['request_token']= (auth.request_token.key,
auth.request_token.secret)
except tweepy.TweepError:
print 'Error! Failed to get request token'
#this is twitter's url for authentication
return flask.redirect(redirect_url)
@app.route("/verify")
def get_verification():
#get the verifier key from the request url
verifier= request.args['oauth_verifier']
auth = tweepy.OAuthHandler(CONSUMER_TOKEN, CONSUMER_SECRET)
token = session['request_token']
del session['request_token']
auth.set_request_token(token[0], token[1])
try:
auth.get_access_token(verifier)
except tweepy.TweepError:
print 'Error! Failed to get access token.'
#now you have access!
api = tweepy.API(auth)
#store in a db
db['api']=api
db['access_token_key']=auth.access_token.key
db['access_token_secret']=auth.access_token.secret
return flask.redirect(flask.url_for('index'))
@app.route("/index")
def index():
#auth done, app logic can begin
api = db['api']
#example, print your latest status posts
return flask.render_template('tweets.html', tweets=api.user_timeline())
if __name__ == '__main__':
app.run()
错误讯息......
* Running on http://127.0.0.1:5000/
* Restarting with reloader
Error! Failed to get request token
127.0.0.1 - - [10/Jul/2014 20:16:14] "GET / HTTP/1.1" 302 -
Error! Failed to get request token
127.0.0.1 - - [10/Jul/2014 20:16:16] "GET / HTTP/1.1" 302 -
Error! Failed to get request token
127.0.0.1 - - [10/Jul/2014 20:16:18] "GET / HTTP/1.1" 302 -
Error! Failed to get request token
127.0.0.1 - - [10/Jul/2014 20:16:20] "GET / HTTP/1.1" 302 -
Error! Failed to get request token
127.0.0.1 - - [10/Jul/2014 20:16:21] "GET / HTTP/1.1" 302 -
Error! Failed to get request token
答案 0 :(得分:1)
原来问题是因为tweepy软件包没有更新到Pypi的最新版本..我从他们的github repo安装它并且它工作正常...
答案 1 :(得分:0)
未从配置文件中正确读取consumer_key和consumer_secret。您可以通过在代码开头对这些键进行硬编码来测试它。其他一切似乎都很好,对我有用!
答案 2 :(得分:0)
我注意到tweepy需要一些更新。看来OauthHandler无法从Python文件夹结构正确加载。我仍在学习导入结构的工作原理。
如果我转到安装了Tweepy库的安装路径,然后将auth.py文件复制到我的本地工作目录中,并重命名为auth_temp.py。然后,我可以毫无问题地访问其中的OAuthHandler类。