我正在尝试使用 Gmail API 通过 Flask-Authlib 访问电子邮件。用户授权后,服务器将在会话中放置一个访问令牌,然后将其定向到反应路由/test
。在由 调用的反应组件中/test
,它将向GET
后端中的另一个方法发送请求以获取电子邮件信息,但是,尽管我将会话生命周期设置得足够长,但访问令牌不再存在。
所以流程是这样的:登录 -> 授权(返回前端) -> 向后端发送 Get 请求/index
。
任何帮助,将不胜感激。
服务器:
@app.route('/index')
def index():
print(get_access_token()) # does not work
if 'access_token' in session:
me = gmail.get('userinfo')
user_id = me.data['id']
access_token = get_access_token()
start = time.time()
inbox = Inbox(gmail, access_token, user_id)
emails = inbox.emails
end = time.time()
return jsonify({
"emails": emails,
'me': user_id,
'count': len(emails),
'time': end - start,
'request time': inbox.request_time
})
return jsonify({
'status': 403,
'session': session.get('access_token')
})
@app.route('/login')
def login():
return gmail.authorize(callback=url_for('authorized', _external=True))
@app.route('/logout')
def logout():
session.pop('access_token', None)
return redirect(url_for('index'))
@app.route('/authorized')
def authorized():
resp = gmail.authorized_response()
if resp is None:
return 'Access denied: reason={} error={}'.format(
request.args['error_reason'],
request.args['error_description']
)
session['access_token'] = (resp['access_token'], '')
print(get_access_token()) # works
return redirect('test')
@gmail.tokengetter
def get_access_token():
return session.get('access_token')
客户:
const Test = React.createClass({
componentDidMount() {
fetch('/index')
.then(response => {
return response.json()
})
.then(json => {
console.log(json)
})
.catch(ex => {
console.log(ex)
})
},
render() {
return (
<div>
tsetdsfadsf
</div>
)
}
})
render((
<Router history={history}>
<Route component={App}>
<Route path="/" component={Index} />
<Route path="/test" component={Test} />
</Route>
</Router>
), document.getElementById('content'))