如何继续Flask.会话oath2调用时的对象

2024-10-03 15:23:00 发布

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

我通过oauth2编写新浪微博客户端,为已经使用我自己网站帐户登录的当前用户添加身份验证,因为oauth2使用重定向回调机制,在这个例程之后,在回调视图处理程序中烧瓶.会话完全是一个新事物。因此我失去了当前用户的登录状态。在

但是在同一个浏览器(比如Firefox)中添加一个新标签并访问我的网站主页(www.funfunsay.com网站),会话对象仍然存在!在

所以有两个烧瓶.会话在同一个浏览器实例中???在

我写了一个非常简单的模块,它与新浪微博很好,只是我失去了旧的会话。在

# -*- coding: utf-8 -*-

from flask import (Flask, render_template, current_app, request,
                   flash, url_for, redirect, session, g, abort)


# For import *
__all__ = ['create_app']

app = Flask(__name__)
app.config['DEBUG'] = True
app.secret_key = 'secret key'

@app.before_request
def before_request():
    print "before request:", session
    #<1st output>for first visit www.funfunsay.com, the output is: before request: <SecureCookieSession {}>
    #<3rd output>for callback from sina, the output is the same

@app.after_request
def after(response):
    print "after request:", session
    #<2nd output>for first visit www.funfunsay.com, the output is: after request: <SecureCookieSession {'testinfo': 'abc'}*>
    return response


@app.route('/')
def hello_world():
    print "request:", request
    login_uri = 'https://api.weibo.com/oauth2/authorize?redirect_uri=http%3A//funfunsay.com/connect/sina/callback&response_type=code&client_id=3921006605&display=default'

    session['testinfo'] = 'abc' #a key-value for test

    return redirect(login_uri)

@app.route("/connect/sina/callback")
def connect_sina_callback():
    print "connect_sina_callback: ", session
    #<4th output>will output: connect_sina_callback:  <SecureCookieSession {}>
    return 'Callback success!'

if __name__ == '__main__':
    app.run('0.0.0.0', 80)

注:出于测试目的,我添加了“127.0.0.1www.funfunsay.com网站“在我的主机文件中。在


Tags: comappforoutput网站requestsessiondef
2条回答

只要保持域名的一致性。我的解决方案是永远使用”www.my-web-site.com,如果用户输入“我的网络-site.com网站,将它们重定向到www.my-web-site.com". 现在一切都好了!在

Flask为来自不同来源点的每个请求分配一个新的会话,因此即使地址解析为同一个IP,来自不同起始点的每个请求也将分配一个不同的会话。E、 g.从http://localhost:5000开始的浏览器窗口将被分配一个与指向http://127.0.0.1:5000的同一浏览器窗口中的选项卡不同的会话……即使这两个窗口解析到相同的位置。在

这可能会令人沮丧,因为一个会话中的数据将无法用于同一浏览器中的另一个选项卡,正如您所期望的那样。。。当您在站点中导航时,一个会话可能很乐意存储您的所有数据,而另一个选项卡将有一个空的session变量。在

在处理OAuth回调时,当我需要确保回调URL(在发送请求的服务器上定义的,例如,当您使用数据提供程序定义OAuth应用程序时)与我启动请求的站点匹配时,这一点最为棘手。例如,如果Github API Developer页面中的OAuth应用程序设置将回调URL列为http://localhost:5000/callback,则我无法将浏览器指向http://127.0.0.1:5000,因为回调将在新会话中启动,会话数据为空。在

幸运的是,这很容易调试(至少在localhost上开发):请确保使用与在数据提供者的OAuth应用程序设置中定义回调URL相同的主机格式测试站点(当您在Facebook、Twitter或Github OAuth API面板中定义应用程序时)。在

相关问题 更多 >