I have a registration form that upon submission, I want to perform some data validation via some external APIs, then eventually submit to another API. I want to do this asynchronously so the submitter is not waiting 10 seconds for the form to submit.
This is my code so far -- it works, but if an exception is thrown in the task, the user gets a 500 error (the specific exception is that sometimes a third party API I use times out). My impression was that if the task is executed asynchronously (notice the @task decorator and using delay to call the task), then the success page load should happen regardless of what happens in the function.
views.py
from myapp.tasks import prepare_and_submit_data
def register(request):
form = SignupForm(request.POST or None)
if form.is_valid():
# Async function.
prepare_and_submit_data.delay(form.cleaned_data)
return render(request, 'success.html', {})
return render(request, 'signup.html', {'form': form})
tasks.py
from celery.decorators import task
@task
def prepare_and_submit_data(data):
# do some external API requests and modify data
data = requests.post(BASE_URL, data=data).json()
# ...
Is the right solution to wrap the contents of the prepare_and_submit_data with a try/except clause and log the error? Or wrap the calling of the function in register?
Thank you.