Reputation: 2773
Given a request, is there a way in django to first return a response and then keep doing some work like updating the DB?
This is for performance reasons. I want the users to receive their response very fast, but DB updates take some time.
Thanks.
Upvotes: 1
Views: 492
Reputation: 111265
If you are using uwsgi with enable-threads = true
then a simple solution would be:
import threading
def myview(request):
obj = MyObj()
threading.Thread(target=save_to_db, args=(obj,)).start()
return ...
def save_to_db(obj):
obj.save()
This is good enough for an occasional background task, if you want to handle every user request this way then some sort of a message queue would be a more scalable solution.
Upvotes: 2
Reputation:
No. Regular Django follows a request-response pathway, so using a pure Django solution, its not possible to return a response and then update a database.
Depending on your requirements, you will probably want to look into a message broker system such as Django channels or Django-celery.
Upvotes: 1
Reputation: 196
Something I am currently investigating: django channels You could queue a message to update the DB and send the response in the mean time. Then another worker will get that message and do the work. However, django-channels does not ensure that your message will not be lost (it ensures it will arrive once at most)... so if the DB update is very important, you might wanna look for something more reliable.
Never tested this yet... just a thought
Upvotes: 1
Reputation: 2600
You could multithread it so one thread returns the response and the second does the task. The other alternative is to pass it off to a message service (along the lines of celery + redis/rabbitmq) and let it handle the task.
Upvotes: 0