问题描述
我要完成的序列:
用户点击网页上的按钮 mod.py中的一些函数开始运行。例如,通过爬行互联网来收集一些数据 函数完成后,结果将返回给用户。我应该在mod.py中打开一个新线程来执行我的函数吗?如果是,我该如何执行此操作?
推荐答案
是的,它可以多线程,但通常用芹菜来做同样的事情。You can read about how in the celery-django tutorial. 很少有实际要强制用户等待网站的情况。虽然这比冒着暂停的风险要好。这是您所描述的示例。
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.
更好的方式:
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