微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Flask Session 和 Google Oauth

如何解决Flask Session 和 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

Google Oauth 的 Settings.yaml:

client_config_backend: file
save_credentials: True
save_credentials_backend: file
save_credentials_file: credentials.json

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。