Django可以做多线程的工作吗?

时间:2021-11-24 21:14:04

I have a question, that can Django do multi-thread works?

我有一个问题,Django可以做多线程的工作吗?

Here is what I want to do: click a button on a web page, then there are some functions in model.py starts to run, for example, crawl some data from internet, when finished, it returns to user the results.

这就是我想要做的:单击网页上的按钮,然后在model.py中开始运行一些功能,例如,从互联网抓取一些数据,完成后,它会返回给用户结果。

I wonder that I have to open a new thread to execute the functions in model.py, can anybody tell me how to do it? Thank you very much.

我想我必须打开一个新的线程来执行model.py中的函数,有人能告诉我该怎么做吗?非常感谢你。

2 个解决方案

#1


10  

  1. Yes it can multi-thread, but generally one uses Celery to do the equivalent. You can read about how in the celery-django tutorial.
  2. 是的它可以是多线程的,但通常一个人使用Celery来做同等的事情。您可以在celery-django教程中了解如何操作。
  3. It is rare that you actually want to force the user to wait for the website. While it's better than risks a timeout.
  4. 您实际上想要强迫用户等待网站是很少见的。虽然它超过了超时的风险。

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 

#2


0  

If you don't want to add some overkill framework to your project, you can simply use subprocess.Popen:

如果您不想在项目中添加一些overkill框架,可以使用subprocess.Popen:

def my_command(request):
    command = '/my/command/to/run'  # Can even be 'python manage.py somecommand'
    subprocess.Popen(command, shell=True)
    return HttpResponse(status=204)

#1


10  

  1. Yes it can multi-thread, but generally one uses Celery to do the equivalent. You can read about how in the celery-django tutorial.
  2. 是的它可以是多线程的,但通常一个人使用Celery来做同等的事情。您可以在celery-django教程中了解如何操作。
  3. It is rare that you actually want to force the user to wait for the website. While it's better than risks a timeout.
  4. 您实际上想要强迫用户等待网站是很少见的。虽然它超过了超时的风险。

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 

#2


0  

If you don't want to add some overkill framework to your project, you can simply use subprocess.Popen:

如果您不想在项目中添加一些overkill框架,可以使用subprocess.Popen:

def my_command(request):
    command = '/my/command/to/run'  # Can even be 'python manage.py somecommand'
    subprocess.Popen(command, shell=True)
    return HttpResponse(status=204)