[英]Django HttpResponseForbidden raised without calling view function
[英]django HttpResponseForbidden not working
我在is_send_permitted_interceptor處將此代碼除外,如果為true則停止處理並重定向到禁止。 但是,它沒有,而是返回了函數中的HttpResponseForbidden對象。
我實際上如何使HttpResponseForbidden()在此上下文中運行。
@login_required
def process_all(request):
#If we had a POST then get the request post values.
if request.method == 'POST':
batches = Batch.objects.for_user_pending(request.user)
# Will redirect/cancel request if user does not meet requirements, funds, permissions etc
is_send_permitted_interceptor(request)
# stuff here if everything is ok
def is_send_permitted_interceptor(request):
# Check user has required credits in account to these batches.
balance = Account.objects.get(user=request.user).get_balance()
cost_of_sending = Batch.objects.batches_cost_pending(user=request.user)
if balance < cost_of_sending:
return HttpResponseForbidden()
else:
pass
您需要在調用者中添加return
,因為您的check函數將要返回給調用者,並且它的值就是您要返回到瀏覽器的值。
更好的方法如下:
def is_send_permitted_interceptor(user):
# Check user has required credits in account to these batches.
balance = Account.objects.get(user=user).get_balance()
cost_of_sending = Batch.objects.batches_cost_pending(user=user)
return balance < cost_of_sending
然后在您的呼叫者中:
if request.method == 'POST':
batches = Batch.objects.for_user_pending(request.user)
if is_send_permitted_interceptor(request.user):
return HttpResponseForbidden()
這樣,它的view方法就是所有重定向發生的地方。 這樣就避免了傳遞request
。
您不會在process_all
視圖中返回“攔截器”的輸出,因此它永遠不會到達用戶。
只需在攔截器中實現您的邏輯,但僅在需要時從主視圖return
即可。
def is_send_permitted(request):
# Check user has required credits in account to these batches.
balance = Account.objects.get(user=request.user).get_balance()
cost_of_sending = Batch.objects.batches_cost_pending(user=request.user)
if balance < cost_of_sending:
return False
else:
return True
@login_required
def process_all(request):
#If we had a POST then get the request post values.
if request.method == 'POST':
batches = Batch.objects.for_user_pending(request)
# Will redirect/cancel request if user does not meet requirements, funds, permissions etc
if not is_send_permitted_interceptor(request):
return HttpResponseForbidden()
# stuff here if everything is ok
您還可以在此處引發異常:
from django.core.exceptions import PermissionDenied
raise PermissionDenied()
但是,當沒有真正異常的情況發生時,引發異常是個壞習慣。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.