在Web2py app

时间:2015-07-21 04:38:56

标签: python session web2py

正如标题中所述,我想在我的Web2py应用中为0None显示session.counter而不是session.wrong_counter。我已经尝试了大约10种不同的方法来做到这一点,但由于某种原因我没有把它弄好。

这是页面Controller的{​​{1}}:

score

def score(): image = db.pic(request.args(0,cast=int)) or redirect(URL('index')) correct = image.id == session.pic_id next_game = random.randint(1, 35) wrong_counter = [] right_counter = [] if correct: session.counter = (session.counter or 0)+1 right_counter=session.counter if not correct: session.wrong_counter = (session.wrong_counter or 0)+1 wrong_counter=session.wrong_counter return locals() 我有View{{=session.counter}}。在{{=session.wrong_counter}}期间首次访问的网页score会显示session,而另一个会显示1,具体取决于Nonecorrect但是,我希望显示not correct而不是0

我非常感谢一些建议。

1 个答案:

答案 0 :(得分:0)

wrong_counter为真时,只需将correct值初始化为0,并且未设置wrong_counter:

if correct:
    session.counter = (session.counter or 0)+1
    right_counter=session.counter
    if not session.wrong_counter:
       # This is the first time we have a correct answer
       wrong_counter = 0
    else:
       wrong_counter = (session.wrong_counter or 0)+1
    session.wrong_counter = wrong_counter
if not correct:
    session.wrong_counter = (session.wrong_counter or 0)+1
    wrong_counter=session.wrong_counter

这样,它不会将None作为默认值,而是为0。

但是,您已将right_counterwrong_counter设置为循环上方的空列表。如果将它们设置为会话变量的值,它将使您的逻辑更容易:

right_counter = session.counter or 0
wrong_counter = session.wrong_counter or 0

if correct:
   right_counter = int(right_counter) + 1
if not correct:
   wrong_counter = int(wrong_counter) + 1

session.counter = right_counter
session.wrong_counter = wrong_counter