在Python中编写多个决策的最佳方法

时间:2018-05-31 07:29:52

标签: python django if-statement

我有以下实际问题(与Django / Python相关)。

我试图在最有效的Python代码中获得以下内容 - >

有两项需要检查:

  1. 用户是否已登录?如果没有显示登录页面,则检查请求是否是发布请求。
  2. 请求是否为帖子请求?如果没有显示表单,则处理表单

    def upload(request):
    if request.user.is_authenticated:
        if request.method == 'POST':
            form = forms.DocumentForm()
            return HttpResponse('Handle POST and LoggedIn Prefix Form Validation')
        else:
            return HttpResponse('POST but not logged in')
            return render(request, 'upload.html', {'form': form}
    else:
        return HttpResponse('Not Logged In Need to Make Error Landing Page')
    

2 个答案:

答案 0 :(得分:0)

我认为这是相当pythonic ...

def upload(request):
    if not request.user.is_authenticated:
        #return early
        return HttpResponse('Not Logged In Need to Make Error Landing Page')

    # this will only be reached if user authenticated
    if request.method == 'POST':
        form = forms.DocumentForm()
        return HttpResponse('Handle POST and LoggedIn Prefix Form Validation')
    else:
        pass # handle GET

如果您需要检查多个功能中的身份验证,请考虑使用装饰器

@authenticated_users_only(request)
def upload(request):   
    if request.method == 'POST':
        form = forms.DocumentForm()
        return HttpResponse('Handle POST and LoggedIn Prefix Form Validation')
    else:
        pass # handle GET

如果你还不知道怎么写装饰师 - read this

答案 1 :(得分:0)

尽可能避免使用else并使用提前退货

def upload(request):
    if request.user.is_authenticated:
        if request.method != 'POST':
            return HttpResponse('Not Logged In Need to Make Error Landing Page')
        form = forms.DocumentForm()
        return HttpResponse('Handle POST and LoggedIn Prefix Form Validation')

    if request.method == 'POST':
        return HttpResponse('POST but not logged in')