Home>

I want to get data by websocket using asyncio with django custom command.
The reason I use django is because I use ORM and I want to use the data obtained from websocket as a web application.

I tried to make it by inserting a loop into the hundred method from the explanation of HP, but I could not receive any data.

I also added the following statement to setting.py.
os.environ ["DJANGO_ALLOW_ASYNC_UNSAFE"] = "true"

If anyone knows the cause, please give us your opinion.

import asyncio
import json
import websockets
class Command (BaseCommand):
    def handle (self, * args, ** kwargs):
            "" "Start loop" ""
            loop = asyncio.get_event_loop ()
            loop.create_task (self.stream ())
            try: try:
                loop.run_forever ()
            except KeyboardInterrupt:
                exit ()
    async def stream (self):
        uri ='ws: // localhost: 18081/****/websocket'
        async with websockets.connect (uri, ping_timeout = None) as ws:
            while not ws.closed:
                response = await ws.recv ()
                content = json.loads (response)
                score = self.original_method1 (kwargs)
                print ('reveiving')
                self.original_method2 (kwargs)
  • Answer # 1

    It doesn't seem to have to be a Django custom command.
    You can call and use the model created by Django from any program.

    As a reference, I think this page will be helpful.
    The following is an example.

    import django
    sys.path.append ("/ var/www/app") Where # manage.py is
    os.environ.setdefault ('DJANGO_SETTINGS_MODULE','app.settings') # settings.py
    django.setup ()
    from appname import models # model import