0

In Django view, I'm trying to run a process as shown below. *I use Django 3.1.7 and Python 3.9.13:

# "views.py"

from multiprocessing import Process
from django.http import HttpResponse

def test():
    print("Test") 

def call_test(request):
    process = Process(target=test)
    process.start()
    process.join()

    return HttpResponse("Test")

But, I got this error below:

django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.

So, following this answer, I added django.setup() and used ProcessPoolExecutor() as shown below:

# "views.py"

import django
import concurrent.futures
from django.http import HttpResponse

def test():
    django.setup()
    print("Test") 

def call_test(request):
    django.setup()
    with concurrent.futures.ProcessPoolExecutor() as executor:
        feature = executor.submit(test)

    return HttpResponse("Test")

But, the error is not solved as shown below:

django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.

So, how can I run a process in Django view without Apps aren't loaded yet error?

Super Kai - Kazuya Ito
  • 22,221
  • 10
  • 124
  • 129
  • 1
    You put that code in "settings.py", is that your projects settings file? – Abdul Aziz Barkat Nov 09 '22 at 15:36
  • @Abdul Aziz Barkat Yes, of course. – Super Kai - Kazuya Ito Nov 09 '22 at 15:39
  • 1
    Oh, you shouldn't put that code in the settings file calling `django.setup()` will end up running the settings file (for initializing things, like DB connections, etc.) but your setting file itself calls `django.setup()` see the problem there? – Abdul Aziz Barkat Nov 09 '22 at 15:41
  • 1
    Does this answer your question? [How to use multiprocess in django command?](https://stackoverflow.com/questions/63669056/how-to-use-multiprocess-in-django-command) – Abdul Aziz Barkat Nov 09 '22 at 15:41
  • Do you mean the linked question or my comment before that? I'm quite sure the linked question solves your problem the `Process` class doesn't have an initializer but you can quite easily shift to using a `Pool` of processes. – Abdul Aziz Barkat Nov 09 '22 at 15:52
  • @Abdul Aziz Barkat https://stackoverflow.com/questions/63669056/how-to-use-multiprocess-in-django-command doesn't work for me as well. – Super Kai - Kazuya Ito Nov 09 '22 at 15:53
  • "doesn't work" is not really great debugging info... Anyway the general idea is your subprocess has to call `django.setup()` (As the answer to that linked question conveys) you could add it to your `test` function I guess if you don't go with a `Pool` maybe even create a decorator or something if you have multiple functions that need this. – Abdul Aziz Barkat Nov 09 '22 at 15:59

0 Answers0