0

如果 true 停止处理并重定向到禁止,我将在 is_send_permitted_interceptor 排除此代码。但是,它没有,而是在函数中返回 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
4

2 回答 2

2

你需要添加return调用者,因为你的检查函数要返回给调用者,它的值就是你要返回给浏览器的值。

更好的方法如下:

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()

这样,它的视图方法就是所有重定向发生的地方;并且您不必绕道而行request

于 2013-09-02T13:13:55.140 回答
1

您不会在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()

但是当没有真正的异常发生时引发异常是不好的做法。

于 2013-09-02T13:13:24.613 回答