I have a multithreaded django app which creates some objects in separate threads in order to return faster. The created objects are just used to track what the user has done and are not in any way time sensitive.
The view function used to look something like this:
def foo(request):
#... do important computation...
bar(x, y, z)
return HttpResponse()
Everything worked fine here, but when I change it to look like this and use threading:
def foo(request):
#... do important computation...
thread = Thread(target=bar, args=(x, y, z))
thread.start()
if testing_mode:
thread.join()
return HttpResponse()
The second version fails. This is all being done using TransactionTestCase
and mySQL.
Any ideas?
Using threads for offloading request is not so good idea. There are many traps, and few benefits. Main problems (and your question relates to these) are:
Correct ways to do that would be:
PS. Don't try to setup Celery or RQ for tests. You should just mock the task and test it separately.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With