我正在通过oauth2编写新浪微博客户端,为已经使用我自己网站帐户登录的当前用户添加身份验证,因为OAuth2使用重定向回调机制,似乎在这个例程之后,并且在回调视图处理程序中, flask.session 完全是一个新对象。因此我失去了当前用户的登录状态。
但是在同一个浏览器(比如Firefox)中添加一个新标签并访问我网站的主页(www.funfunsay.com),会话对象仍然存在!
所以同一个浏览器实例中有两个flask.session???
我写了一个非常简单的模块,除了我丢失了旧会话之外,它与新浪微博很好。
# -*- 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)
PS:出于测试目的,我在我的主机文件中添加了“127.0.0.1 www.funfunsay.com”。