Flask - session.logged_in未更新

0 投票
1 回答
1688 浏览
提问于 2025-04-18 01:14

我正在写一个简单的Flask应用,首页会要求输入用户名和密码,然后检查这些信息是否有效,如果有效,就把session.logged_in设置为真。我用打印输出检查,发现session.logged_in确实被设置成了“True”。登录后,会有一个HTML页面,上面有一些链接,比如:表格列表(在HTML文件中用{{ url_for('table_list') }}表示)。但是,当我用foreman点击那个链接时,session.logged_in却变成了None(既不是True也不是False)。

我的Python代码是:

from flask import Flask, stream_with_context, request, Response, url_for, render_template, flash, session
...
app = Flask(__name__)
app.debug = True                # Enable debug-mode
app.secret_key = 'nosecret'

def stream_template(template_name, **context):
    app.update_template_context(context)
    t = app.jinja_env.get_template(template_name)
    rv = t.stream(context)
    # uncomment if you don't need immediate reaction
    ##rv.enable_buffering(5)
    return rv

@app.route('/')
def index():
    return render_template('signin.html')

@app.route('/', methods=['POST'])
def login():
    # Read from the from input
    usrn = request.form['username']
    pswd = request.form['password']

    if validate_login(usrn, pswd):
        session['logged_in'] = True
        print 'login1:', session.logged_in
        sys.stdout.flush()
        return Response(stream_with_context(stream_template('index.html', data=genData())))
    else:
        return Response(stream_template('fail.html', code=pswd, username=usrn))

.....
@app.route('/listtable')
def list_table():
    print 'login2:', session.logged_in
    sys.stdout.flush()
    return Response(stream_with_context(stream_template('listtables.html', loginsession=session.logged_in)))

控制台的结果是:

login1: True
login2: none

我觉得问题可能是因为我在某种情况下使用了流式处理,这样就破坏了我当前的session。有没有人知道怎么解决这个问题?非常感谢。

解决方法:我不太确定我的问题是什么,但我创建了一个新的类叫MySession,在我的session里有一个布尔值用来保存登录状态。通过使用MySession类,我可以更新当前的session和我现在拥有的信息,不知道为什么Flask的session对我来说不管用。

1 个回答

0

这里,你可以选择使用装饰器@login_required,或者如果你在函数里需要的话,可以用is_authenticated()这个方法。我觉得你不应该自己去访问数据结构。就连登录,我猜也有一个方法你需要调用,而不是直接在会话中设置True。(你应该使用login_user()这个方法)。你可能还想看看这个

撰写回答