Django 1.6从递归函数返回HttpResponseNotFound()

时间:2014-04-15 17:44:00

标签: python django

有没有办法让返回HttpResponseNotFound()递归返回所以它可以按预期使用?我问的原因是因为我想重新使用get_thread_and_user()并尽可能保持代码DRY。

def get_thread_and_user(request, thread_id):
    try:
        thread_id=777
        thread = ThreadVault.objects.get(thread_id=thread_id)
        user = Employee.objects.get(id=request.user.id)
    #TODO: Fix to broad exception
    except:
        return HttpResponseNotFound(
            '<h1>Oh snap! There\'s a database error!</h1>')
    return thread, user

def assign_thread(request, thread_id):
    thread, user = get_thread_and_user(request, thread_id)

    if thread.assigned_user is None:
        try:
            thread.assigned_user = user
            thread.last_modified_by = user
            thread.save()
         except:
            return HttpResponseNotFound(
                '<h1>Oh snap! There\'s a database error!</h1>')
    else:
        return render_to_response('bot_data/assign_confirm.html',
                {'user' : user})
    return HttpResponseRedirect("http://10.1.55.78:8000/unanswered")

2 个答案:

答案 0 :(得分:3)

而不是返回那个HttpResponse,你应该提出特定的Http404异常,它会冒泡到中间件并返回404消息。

此外,你应该从不抓住一个裸露的除外。始终只捕捉您期望的异常。

except ThreadVault.DoesNotExist, Employee.DoesNotExist:
    raise Http404(
        '<h1>Oh snap! There\'s a database error!</h1>')

答案 1 :(得分:2)

返回get_thread_and_user

的结果
def get_thread_and_user(request, thread_id):
    return HTTPResponseNotFound("Error  TIME!")

def assign_thread(request, thread_id):
     return get_thread_and_user(request, thread_id)

您也可以将raise作为例外。这将跳出整个视图流程。只要你没有except它就会冒泡进入框架并将正确的代码返回给用户。