1

I am running a development server locally

python manage.py runserver 8000

Then I run a script which consumes the Consumer below

from channels.generic.websocket import AsyncJsonWebsocketConsumer

class MyConsumer(AsyncJsonWebsocketConsumer):
    async def connect(self):
        import time
        time.sleep(99999999)
        await self.accept()

Everything runs fine and the consumer sleeps for a long time as expected. However I am not able to access http://127.0.0.1:8000/ from the browser.

The problem is bigger in real life since the the consumer needs to make a HTTP request to the same server - and essentially ends up in a deadlock.

Is this the expected behaviour? How do I allow calls to my server while a slow consumer is running?

Pithikos
  • 18,827
  • 15
  • 113
  • 136

1 Answers1

1

since this is an async function you should but using asyncio's sleep.

import asyncio

from channels.generic.websocket import AsyncJsonWebsocketConsumer

class MyConsumer(AsyncJsonWebsocketConsumer):
    async def connect(self):
        await asyncio.sleep(99999999)
        await self.accept()

if you use time.sleep you will sleep the entire python thread.

this also applies to when you make your upstream HTTP request you need to use an asyncio http library not a synchronise library. (basically you should be awaiting anything that is expected to take any time)

Matthaus Woolard
  • 2,310
  • 11
  • 13
  • Thank you. I assumed purely using `async` made the function asynchronous and thus non-blocking – Pithikos Feb 13 '20 at 14:14
  • in python what the `await` does is effectively let the thread be able to jump away and work on something else and then when the thing you were awaiting is ready you can jump back here. Without it in python you are still all single threaded. – Matthaus Woolard Feb 13 '20 at 17:29