multiprocessing.Process.start()引发异常django.core.exceptions.AppRegistryNotReady

时间:2018-07-19 20:51:50

标签: python django python-3.x multiprocessing python-multiprocessing

Views.py

def time_consuming_task_caller(time_to_sleep, j):
    print ('start', task_id)
    # time.sleep(time_to_sleep)
    # print('finished', task_id)


def time_consuming_task_caller(time_to_sleep, j):
    Process(target=time_consuming_task, args=(time_to_sleep, task_id)).start()
    print ('processing...', task_id)
    return {'one': 'two'}


def get_task(request):
    if request.method == 'GET':
        response = time_consuming_task_caller(5,1) # 5 is like time to sleep, 1 is task id.
        print(response)

    return HttpResponse(json.dumps(response), content_type="application/json")

这会导致在return HttpResponse(json.dumps(response), content_type="application/json")处出错,因为它会打印所有三个打印语句(注释的语句除外)

即使使用time.sleep()进行注释,也会导致错误。最终目标是使它适用于可能需要更长执行时间的流程。

编辑

urls.py

urlpatterns = [
    path('api/', get_task ,name='run')
]

错误

Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "c:\users\user\appdata\local\programs\python\python36\Lib\multiprocessing\spawn.py", line 105, in spawn_main
    exitcode = _main(fd)
  File "c:\users\user\appdata\local\programs\python\python36\Lib\multiprocessing\spawn.py", line 115, in _main
    self = reduction.pickle.load(from_parent)
  File "D:\Programming\django_project\webapp - Dev\server 3\manager\utils.py", line 1, in <module>
    from .models import Task
  File "D:\Programming\django_project\webapp - Dev\server 3\manager\models.py", line 2, in <module>
    from accounts.models import CustomUser
  File "D:\Programming\django_project\webapp - Dev\server 3\accounts\models.py", line 2, in <module>
    from django.contrib.auth.models import AbstractUser
  File "D:\Programming\django_project\env_django\lib\site-packages\django\contrib\auth\models.py", line 2, in <module>
    from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager
  File "D:\Programming\django_project\env_django\lib\site-packages\django\contrib\auth\base_user.py", line 47, in <module>
    class AbstractBaseUser(models.Model):
  File "D:\Programming\django_project\env_django\lib\site-packages\django\db\models\base.py", line 100, in __new__
    app_config = apps.get_containing_app_config(module)
  File "D:\Programming\django_project\env_django\lib\site-packages\django\apps\registry.py", line 244, in get_containing_app_config
    self.check_apps_ready()
  File "D:\Programming\django_project\env_django\lib\site-packages\django\apps\registry.py", line 127, in check_apps_ready
    raise AppRegistryNotReady("Apps aren't loaded yet.")
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.

1 个答案:

答案 0 :(得分:1)

您提供的堆栈跟踪记录中的错误也可能是由您的models文件(您未包含)引起的。

但是实现此类功能的正确方法是使用任务运行程序,例如 celery