Question
The sequence I would like to accomplish:
- A user clicks a button on a web page
- Some functions in model.py start to run. For example, gathering some data by crawling the internet
- When the functions are finished, the results are returned to the user.
Should I open a new thread inside of model.py to execute my functions? If so, how do I do this?
Answer
- Yes it can multi-thread, but generally one uses Celery to do the equivalent. You can read about how in the celery-django tutorial.
- It is rare that you actually want to force the user to wait for the website. While it's better than risks a timeout.
Here's an example of what you're describing.
User sends request
Django receives => spawns a thread to do something else.
main thread finishes && other thread finishes
... (later upon completion of both tasks)
response is sent to user as a package.
Better way:
User sends request
Django receives => lets Celery know "hey! do this!"
main thread finishes
response is sent to user
...(later)
user receives balance of transaction