Skip to main content
 首页 » 编程设计

python之带有 flask_oauthlib 的 Twitter oauth,无法生成请求 token

2025年04月02日14zhujiabin

我尝试使用 flask_oauthlib 访问我的 Twitter API,但我得到的只是错误:无法生成请求 token 。这是代码。

    from flask_oauthlib.client import OAuth 
    from flask import Flask, url_for, request, jsonify 
 
    app = Flask(__name__) 
    oauth = OAuth() 
 
    twitter = oauth.remote_app( 
        'twitter', 
        base_url='https://api.twitter.com/1/', 
        request_token_url='https://api.twitter.com/oauth/request_token', 
        access_token_url='https://api.twitter.com/oauth/access_token', 
        authorize_url='https://api.twitter.com/oauth/authorize', 
        consumer_key='dOJjyxB6gxXWTjdtfPUZcZPjl', 
        consumer_secret='im not telling you', 
    ) 
 
 
    @app.route('/login') 
    def login(): 
        return twitter.authorize(callback=url_for('authorized', 
                                                  next=request.args.get('next') or request.referrer or None)) 
 
 
    @app.route('/authorized') 
    @twitter.authorized_handler 
    def authorized(resp): 
        if resp is None: 
            return 'Access denied: error=%s' % ( 
                request.args['error'] 
            ) 
        if 'oauth_token' in resp: 
            # session['example_oauth'] = resp 
            print(resp) 
            return jsonify(resp) 
        return str(resp) 
 
 
    if __name__ == '__main__': 
        app.run(port=8000, debug=True) 
 

这在使用 http://term.ie/oauth/example/client.php 时不起作用,我设法获得了一个请求 token 。

我用 https://github.com/lepture/example-oauth1-server/blob/master/client.py 启发了自己和 http://flask-oauthlib.readthedocs.io/en/latest/client.html

编辑

奇怪的事实:我在这里试过代码:https://github.com/lepture/flask-oauthlib/blob/master/example/twitter.py 我没有更改 key 和密码,它起作用了。

因此,我尝试将它们更改为我自己的凭据,但它停止了工作。实在看不懂……

请您参考如下方法:

好的,我发现了问题。使用 flask-oauthlib 时,回调 URL 似乎是必需的。所以我添加了一个假的,因为我还在本地主机上,它解决了这个问题。