如何从重定向u获取访问令牌

2024-03-29 14:32:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我想从Spotify得到一个access token。我从Spotify得到一些信息:

https://example.com/callback#access_token=NwAExz...BV3O2Tk&token_type=Bearer&expires_in=3600&state=123

我在地址栏看到了。其中https://example.com/callback是我的站点,access_token是需要的值。如何得到它?你知道吗

我试过这样,但是得到None

print(flask.request.args.get('access_token'))

完整代码

import flask 
app = flask.Flask(__name__)

@app.route("/")
def render_index():
    return flask.render_template('index.html')

@app.route("/redirect_spotify_token", methods = ['POST'])
def redirect_spotify_token():
    return flask.redirect('https://accounts.spotify.com/authorize?...')

@app.route("/callback/spotify_token", methods = ['POST', 'GET'])
def callback_token():
  #
  # how to get access token?
  #
  return 'ok'

if __name__ == "__main__":
  app.run(host='0.0.0.0', port=8080) 

Tags: httpscomtokenappflaskgetreturnaccess
1条回答
网友
1楼 · 发布于 2024-03-29 14:32:04

我通过服务repl.it完成我的项目。也许这就是为什么我不能像这样读request的args

flask.request.args.get('access_token')

解决方案

从Spotify重定向到/callback_token。在这种情况下,函数argtokenNone。我的页面callback_token.html是解析url并用token重定向到callback_token()。你知道吗

主.py

@app.route("/callback_token")
@app.route("/callback_token/<token>")
def callback_token(token=None):
    if token is None:
      return render_template('callback_token.html')
    else:
      #logic with token
      return redirect(url_for('index'))

回拨_令牌.html使用javascript

var parsedHash = new URLSearchParams(
    window.location.hash.substr(1)
);
location.href = `your_url.com/callback_token/${parsedHash.get('access_token')}`

相关问题 更多 >