[Answer]-Django: views and assert like returns

1👍

What about an exception, and a nice decorator to catch it:

class AssertError(Exception):
    pass

def assertLike(view):
    def wrap(request, *args, **kwargs):
        try:
            return view(request, *args, **kwargs):
        except AssertError as e:
            return HttpResponseServerError(...)
    return wrap

@assertLike
def createTask(request):
    import json
    ....
    if not exp:
        raise AssertError()
    ....
    return HttpResponse("Ok")

0👍

Here I present the generator based solution:

def assertLike(view):
    def wrap(request, *args, **kwargs):
        for response in view(request, *args, **kwargs):
            if response:
                return response
    return wrap


@other_django_views
@another_django_view
@assertLike
def createTask(request):
    import json

    def err(msg=None):
        msg = msg if msg else "Illegal Parameters"
        resp = {"msg": msg}
        resp = json.dumps(resp)
        return HttpResponseServerError(resp)

    def verify(exp, msg=None):
        if not exp:
            return err(msg)

    # only react to ajax requests
    yield verify(True, "This is not an error")
    yield verify(False, "Here it should stop!")

    yield HttpResponse("This is the final response!")

Leave a comment