我尝试调用一个检查规则的函数,如果不满足规则,我想跳过其余的 View 代码,只返回一个 HttpResponse 错误。
我想将所有转义逻辑放在一个函数中,因为我在整个项目中的多个点都需要它。
我试图做这样的事情:
def myView(request):
checkFunction()
还有:
def checkFunction():
#do stuff
return HttpResponse(status=403)
但它就是行不通(难怪)......
任何想法如何正确地做到这一点?
谢谢
罗恩
最佳答案
你的错误是,在 myView
函数中,你调用了你的 checkFunction
,但是你没有使用 checkFunction
的返回值所以你的返回checkFunction
return HttpResponse(status=403)
的值丢失并且从未在 myView
中返回。
可能是这样的:
def myView(request):
result = checkFunction()
if result:
return result
#if no problem, keep running on...
def checkFunction():
#do stuff
if something_goes_wrong:
return HttpResponse(status=403)
# you do not need to return anything if no error occured...
所以,如果没有出错,那么 checkFunction
将不会返回任何内容,并且 result
将是 None
和 if 结果:
block 不会被执行。如果您返回响应,那么您的 View 将返回该响应(在您的情况下,HttpResponse(status=403)
)...
更新:那么你可以这样做......
def checkFunction(request):
#do stuff
if something_goes_wrong:
return HttpResponse(status=403)
elif some_other_issue:
return HttpResponse(....)
else: #no problems, everything is as expected...
return render_to_response(...) # or any kind of response you want
def myView(request):
return checkFunction(request)
这样,您的 View 将返回您的 checkFunction
返回的内容...
此外,将 request
对象传递给您的 checkFunction
可能是必要的,因为您希望在那里创建响应。你可能需要它。
关于Django - 是否可以从 View 中的函数进行重定向?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11137309/