Ron*_*Ron 2 django return view httpresponse decorator
我尝试调用一个检查规则的函数,如果规则未满足,我想跳过其余的视图代码,只返回一个HttpResponse错误.
我想将所有转义逻辑放在一个函数中,因为我需要在我的项目中的几个点上.
我试着这样做:
def myView(request):
checkFunction()
Run Code Online (Sandbox Code Playgroud)
和:
def checkFunction():
#do stuff
return HttpResponse(status=403)
Run Code Online (Sandbox Code Playgroud)
但它只是不起作用(难怪)......
任何想法如何做到这一点?
谢谢
罗恩
你的错误是,在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...
Run Code Online (Sandbox Code Playgroud)
所以,如果一切正常,那么checkFunction将不会返回任何东西,result会None和if result:块将不会被执行.如果您返回响应,则视图将返回该响应(在您的情况下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)
Run Code Online (Sandbox Code Playgroud)
这样,您的视图将返回您的checkFunction回报...
此外,将request对象传递给您checkFunction可能是必要的,因为您希望在那里传播您的响应.你可能需要它.
| 归档时间: |
|
| 查看次数: |
1844 次 |
| 最近记录: |