python - Flask 会话和 Google Oauth
问题描述
我正在开发一个简单的 Web 应用程序,以使用 Flask 会话和 Google OAuth 列出当前登录用户的 google 驱动器信息。我正在使用 Nginx 和 WSGI 运行 DO droplet 来为应用程序提供服务。当我在本地测试应用程序时,它按预期工作,我可以使用 google Oauth 登录应用程序。但是,当我将应用程序上传到 droplet 时,我似乎在登录并被重定向后丢失了会话。该应用程序当前的编写方式,即使在成功登录后,它也会一直让我进入登录页面。我不太确定我错过了什么,或者为什么它只发生在服务器上而不是我的本地机器上。
应用:
from flask import Flask, redirect,request, session, abort, render_template
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
import secrets
app = Flask(__name__)
secret_key = secrets.token_hex(16)
app.config['SECRET_KEY'] = secret_key
@app.route('/')
def index():
if not session.get('logged_in'):
return render_template('login.html')
drive = getDrive()
return render_template('index.html')
@app.route('/login', methods = ['POST'])
def login():
gauth = GoogleAuth()
auth_url = gauth.GetAuthUrl()
session['logged_in'] = True
return redirect(auth_url, code=302)
def getDrive(drive=None, gauth=None):
if not drive:
if not gauth:
gauth = GoogleAuth()
gauth.LoadCredentialsFile()
if gauth.access_token_expired:
try:
gauth.Refresh()
except Exception as e:
print(f'Google Drive Error: {e}')
else:
gauth.Authorize()
return GoogleDrive(gauth)
if drive.auth.access_token_expired:
try:
drive.auth.Refresh()
except Exception as e:
print(f'Google Drive Error: {e}')
return drive
谷歌 Oauth 的 Settings.yaml:
client_config_backend: file
save_credentials: True
save_credentials_backend: file
save_credentials_file: credentials.json
解决方案
推荐阅读
- node.js - 无法弄清楚 Heroku 网站为何输出“无法获取 /”消息
- java - 有没有办法发送可序列化类的不同子类的实例?
- c# - 如何使用 Linq 订购两个 DatetimeOffset 属性
- docker - 在 docker 卷中持久化 apache nifi flow.xml.gz 文件
- html - 如何将自定义formio组件添加到表单管理器
- c++ - 使用模板函数进行通用输入验证
- numpy - 从头开始在 Keras 中编写自己的卷积层
- javascript - ES6 导出模板生成器
- android - 如何编写和读取具有自定义扩展名的文本文件?
- php - HTML代码转换为pdf文件时的Dompdf表格边框问题