How to simulate two parallel requests in django testing framework

Viewed 245

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?

1 Answers

I suggest you use an async loop to trigger 2 quite simultaneous request.

Example:

async def test_case(request):
    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})


async def simult(request):
    t_case_0 = await test_case(request)
    t_case_1 = await test_case(request)

asyncio.run(simult(request))
Related