What's the easiest way to iterate over Django's view on raising an exception?

I want to rerun the Django view function if a specific exception is thrown (in my case, a serialization error on the underlying database). I want it to work with exactly the same parameters, including the same object request

, as if the client re-requested the url.

There are many database queries in the view, and an exception can be raised on any of them - and it won't work to rerun just one of the queries individually, so I think I need to wrap the whole kind of function in a try / except block and loop until it succeeds.

But I have several view functions that can throw exceptions like this, so I want to use a generic solution. I also want to be able to retry up to a certain number of times and then fail.

Is there any simple solution?

+3


source to share


1 answer


You can achieve this by writing a decorator:

def retry_on_exception(view):
    def wrapper(*args, **kwargs):
        while True:
            try:
                return view(*args, **kwargs):
            except (TheExceptions, IWant, ToCatch):
                pass
    return wrapper

      

And use this in a view:



@retry_on_exception
def my_view(request, foo, bar):
    return HttpResponse("My stuff")

      

Obviously this will take forever, so the logic could be improved there. You can also write to the decorator to accept the exceptions it wants to notice, so you can customize it for each kind.

+4


source







All Articles