0

我为我的 django 应用程序编写了两个非常简单的装饰器:

def login_required_json(f):
    def inner(request, *args, **kwargs):
        #this check the session if userid key exist, if not it will redirect to login page
        if not request.user.is_authenticated():
            result=dict()
            result["success"]=False
            result["message"]="The user is not authenticated"
            return HttpResponse(content=simplejson.dumps(result),mimetype="application/json")
        else:
            return f(request, *args, **kwargs)

def catch_404_json(f):
    def inner(*args,**kwargs):
        try:
            return f(*args, **kwargs)
        except Http404:
            result=dict()
            result["success"]=False
            result["message"]="The some of the resources throw 404"
            return HttpResponse(content=simplejson.dumps(result),mimetype="application/json")

但是当我将它们应用于我的视图时,我在模板中收到“ViewDoesNotExist”错误,说它无法导入视图,因为它不可调用。我究竟做错了什么?

4

1 回答 1

3
def login_required_json(f):
    def inner(request, *args, **kwargs):
        #this check the session if userid key exist, if not it will redirect to login page
        if not request.user.is_authenticated():
            result=dict()
            result["success"]=False
            result["message"]="The user is not authenticated"
            return HttpResponse(content=simplejson.dumps(result),mimetype="application/json")
        else:
            return f(request, *args, **kwargs)

    return inner   # <--- Here

您的装饰器返回 None,而不是实际视图。所以返回我上面演示的内部函数。

于 2012-10-24T13:21:49.727 回答