I have a Django application (using uWSGI and nginx, and atomic views) with a view that creates new items of a model in the DB (postgres). Before creating anything the view checks if the record doesn't already exist in the DB, something like:
...
try:
newfile = DataFile.objects.get(md5=request.POST['md5'])
except DataFile.DoesNotExist:
newfile = DataFile.objects.create(md5=request.POST['md5'], filename=request.POST['filename'])
return JsonResponse({'file_id': newfile.pk})
I noticed sometimes this doesn't work, and I get duplicates in the DB (which is easily solved with a unique constraint). I'm not sure why this happens, if there is caching or race conditions, but I'd like to at least cover the behaviour with a test in the Django test framework.However, I do not know how to simulate two parallel requests. Is there a way to fire the next request while not waiting for the first, built into the framework, or should one use multiprocessing or similar for this?