简体   繁体   English

在django视图中测试django会话变量并返回

[英]Testing a django session variable in a django view and return

I am trying to perform a selective operation based on the sessions variables set. 我正在尝试根据会话变量集执行选择性操作。

This is how I try- 这就是我尝试的方式

   try:
        if request.session.get('firstoption', False):
            # perform operation for first option
            return redirect(reverse('first_option_view'))
    except:
        try:
            if request.session.get('secondoption', False):
                # perform operation for second option
                return redirect(reverse('second_option_view'))
        except:
            return HttpResponse("WTF!")

The execution hits the first if request.session.get('firstoption', False): it returns none, in the case of second case, instead of going to except, it returns the following error - views.viewname didn't return an HttpResponse object . if request.session.get('firstoption', False):第一个if request.session.get('firstoption', False): ,执行将返回第一个:在第二种情况下,它不返回任何内容,而不是返回到,而是返回以下错误views.viewname didn't return an HttpResponse object

What am I doing wrong? 我究竟做错了什么?

The get is returning None or False, but not an exception; get返回的是None或False,但不是异常。 your if is thus not executing the yes branch, but this is not an exception. 您的if因此不执行yes分支,但这也不例外。 You are simply then skipping the rest of the code and exiting the function without returning anything. 然后,您只需跳过其余代码并退出函数而不返回任何内容。 You should have an else. 你应该有别的。

If you are not expecting any exceptions then you will not need a try except block. 如果您不希望有任何异常,则无需尝试try除外块。

if request.session.get('firstoption', False):
    # perform operation for first option
    return redirect(reverse('first_option_view'))

if request.session.get('secondoption', False):
    # perform operation for second option
    return redirect(reverse('second_option_view'))

else:
    return HttpResponse("WTF!")

It looks like you should be using a form for this. 看来您应该为此使用表格。 That way you can build in error checking for invalid inputs and many other benefits. 这样,您可以建立错误检查来检查无效输入和许多其他好处。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM