Amir Daghestani
Amir Daghestani

Reputation: 47

"Apps aren't loaded yet" when import model to a file run by manage.py

I want to get cryptocurrency data from external websocket and save it to database. In order to run producer.py from start, I added it to INSTALLED_APPS in settings.py:

INSTALLED_APPS = [
    'crypto.spot.producer',
]

producer.py is:

from .models import Spot


async def message(u, t, interval, timeout):
    async with websockets.connect(uri=u + '?token=' + t, ping_interval=interval, ping_timeout=timeout) as websocket:
        await websocket.send(json.dumps({"id": "4848226",
                                         "type": "subscribe",
                                         "topic": "/market/ticker:all",
                                         "response": True}))
        while True:
            response = await websocket.recv()
            result = json.loads(response)
            '''
            write result to django model (Spot)
            '''


while True:
    response = r.post('https://api.kucoin.com/api/v1/bullet-public')
    payload = json.loads(response.text)

    uri = payload['data']['instanceServers'][0]['endpoint']
    token = payload['data']['token']
    ping_interval = payload['data']['instanceServers'][0]['pingInterval']
    ping_timeout = payload['data']['instanceServers'][0]['pingTimeout']

    asyncio.get_event_loop().run_until_complete(message(uri, token, ping_interval, ping_timeout))
    asyncio.get_event_loop().run_forever()

However, I get the following error:

Watching for file changes with StatReloader
Exception in thread django-main-thread:
Traceback (most recent call last):
  File "C:\Users\a.daghestani\AppData\Local\Programs\Python\Python37\lib\threading.py", line 926, in _bootstrap_inner
    self.run()
  File "C:\Users\a.daghestani\AppData\Local\Programs\Python\Python37\lib\threading.py", line 870, in run
    self._target(*self._args, **self._kwargs)
  File "C:\Users\a.daghestani\AppData\Local\Programs\Python\Python37\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper
    fn(*args, **kwargs)
  File "C:\Users\a.daghestani\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\commands\runserver.py", line 109, in inner_run
    autoreload.raise_last_exception()
  File "C:\Users\a.daghestani\AppData\Local\Programs\Python\Python37\lib\site-packages\django\utils\autoreload.py", line 76, in raise_last_exception
    raise _exception[1]
  File "C:\Users\a.daghestani\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\__init__.py", line 357, in execute
    autoreload.check_errors(django.setup)()
  File "C:\Users\a.daghestani\AppData\Local\Programs\Python\Python37\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper
    fn(*args, **kwargs)
  File "C:\Users\a.daghestani\AppData\Local\Programs\Python\Python37\lib\site-packages\django\__init__.py", line 24, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "C:\Users\a.daghestani\AppData\Local\Programs\Python\Python37\lib\site-packages\django\apps\registry.py", line 91, in populate
    app_config = AppConfig.create(entry)
  File "C:\Users\a.daghestani\AppData\Local\Programs\Python\Python37\lib\site-packages\django\apps\config.py", line 90, in create
    module = import_module(entry)
  File "C:\Users\a.daghestani\AppData\Local\Programs\Python\Python37\lib\importlib\__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
  File "<frozen importlib._bootstrap>", line 983, in _find_and_load
  File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 728, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "C:\Users\a.daghestani\Desktop\marlikfund\crypto\spot\producer.py", line 9, in <module>
    from .models import Spot
  File "C:\Users\a.daghestani\Desktop\marlikfund\crypto\spot\models.py", line 6, in <module>
    class Spot(models.Model):
  File "C:\Users\a.daghestani\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\base.py", line 107, in __new__
    app_config = apps.get_containing_app_config(module)
  File "C:\Users\a.daghestani\AppData\Local\Programs\Python\Python37\lib\site-packages\django\apps\registry.py", line 252, in get_containing_app_config
    self.check_apps_ready()
  File "C:\Users\a.daghestani\AppData\Local\Programs\Python\Python37\lib\site-packages\django\apps\registry.py", line 135, in check_apps_ready
    raise AppRegistryNotReady("Apps aren't loaded yet.")
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.

any idea?

Upvotes: 1

Views: 82

Answers (1)

Mohsen Mahmoodi
Mohsen Mahmoodi

Reputation: 357

You getting this error because you can not access models before django loading is finished. Your module tries to access models while they are not loaded yet.

To solve your problem you should create a django management command or an standalone script which loads and configures django, after that you can run your producer loop and access models without any problem. e.g.

producer.py modeuls:

import sys, os, django
sys.path.append("/path/to/your/project")
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "your-project.settings")
django.setup()


from <your-app>.models import Spot

.... Your script

Don't forget to remove the module (crypto.spot.producer) from INSTALLED_APPS.

Upvotes: 1

Related Questions