Python 如何在会话中弹出第二个值?

Python 如何在会话中弹出第二个值?,python,flask,Python,Flask,我在我的登录系统上有两个会话,“admin”和“standard”,当我单击logout时,我从会话堆栈中弹出“admin”,我想知道如何弹出标准会话 # Logout of System @app.route('/logout') def logout(): session.pop('is_admin') #session.pop('standard') return render_template('/index.html') 我试过的另一种变体,不起作用 # Lo

我在我的登录系统上有两个会话,“admin”和“standard”,当我单击logout时,我从会话堆栈中弹出“admin”,我想知道如何弹出标准会话

# Logout of System
@app.route('/logout')
def logout():
    session.pop('is_admin')
    #session.pop('standard')
    return render_template('/index.html')
我试过的另一种变体,不起作用

# Logout of System
@app.route('/logout')
def logout():
    if 'is_admin' in session:
        session.pop('is_admin')
    return render_template('/index.html')
    if 'is_standard' in session:
        session.pop('standard')
    return render_template('/index.html')

你为什么不试试这个:

@app.route('/logout')
def logout():
    for s in ['is_admin', 'standard']:
        try:
            session.pop(s)
        except KeyError:
            continue
    return render_template('/index.html')
如果存在上述两个键,或仅显示其中一个键,则会弹出上述两个键。 如果你将sobolevn答案中的列表理解结合起来,你的路线就是这样的

@app.route('/logout')
def logout():
    [session.pop(i, None) for i in ['is_admin', 'standard']]
    return render_template('/index.html')
第二种变体应为:

# Logout of System
@app.route('/logout')
def logout():
    if 'is_admin' in session:
        session.pop('is_admin')
        return render_template('/index.html')
    if 'is_standard' in session:
        session.pop('standard')
        return render_template('/index.html')
它的执行速度比我的变体慢,而且更冗长

烧瓶中的会话是一个。以下是您无法迭代会话并从中删除元素的原因:

In [35]: session =  {'std': 'bar', 'admin':'foo', 'manager': 'baz'}

In [36]: for s in session:
    try:
        session.pop(s)
    except KeyError:
        continue
   ....:     
---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
<ipython-input-36-14e9c7f174be> in <module>()
----> 1 for s in session:
      2     try:
      3         session.pop(s)
      4     except KeyError:
      5         continue

RuntimeError: dictionary changed size during iteration
修改会话后,您将得到:

In [41]: for s in ['std', 'admin']:
    try:
        session.pop(s)
    except KeyError:
        print "I didn't find %s" % s
        continue
   ....:     
I didn't find std
I didn't find admin

我希望这能让我的答案更清楚。

好的,这里有一句话:

>>> s = {'is_admin': 1, 'standard': 1}
>>> [s.pop(i, None) for i in ['is_admin', 'standard']]
[1, 1]
>>> s
{}
弹出(键[,默认])

如果键在字典中,请删除它并返回其值,否则 返回默认值。如果未给出默认值且密钥不在 字典中,出现了一个键错误


我认为我在[…]中替换了s,在会话中替换了s:?不,你没有。它将迭代您会话中的所有内容。您只想检查两个项目,对吗?如果会话中只有一个值,会发生什么?当我们向循环提供2时?我已经写过了,如果只有一个存在,它将抛出一个
KeyError
,然后转到第二个,或者finish.yes。这是一种非常简洁的方法。非常像蟒蛇,但对noobs来说有点不可读;-)你还有我的一票!这里的缺点是,您为理解创建的列表分配内存,该列表将立即被丢弃。一个简单的for循环会更好。
>>> s = {'is_admin': 1, 'standard': 1}
>>> [s.pop(i, None) for i in ['is_admin', 'standard']]
[1, 1]
>>> s
{}