首页 > 解决方案 > 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

标签: pythonflaskoauthpydrive

解决方案


推荐阅读