hotwire-django / turbo-django

Unmaintained // An early stage integration of Hotwire Turbo with Django
https://discuss.hotwire.dev/t/django-backend-support-for-hotwire/1570/
Other
385 stars 20 forks source link

Quickstart not working #46

Closed elamje closed 2 years ago

elamje commented 3 years ago

High level: following Quickstart did not result in a working example. With 1 shell running Django web server and one running a Django shell, I was not able to produce expected functionality. It seems that channel broadcasts were lost in the ether. This could be a missing settings, but then again, I would expect to see an error if that were the case.

Info:

// requirements.txt
django==3.1.13
uvicorn[standard]==0.15.0
turbo-django==0.2.4
websockets==10.0
channels==3.0.4
....

OS: OSx 10.15.7 (Catalina)

Please let me know how I can assist.

elamje commented 3 years ago

@scuml Following up - I also cannot reproduce turbo streams behavior using the tutorial as a guide. It seems to be a larger issue than just quickstart not working. I've also tried versions 0.2.0 - 0.2.4 in case it was a minor bump that introduced the issue.

elamje commented 3 years ago

I was able to get the experiments/chat example working. Digging deeper now.

scuml commented 3 years ago

This is a problem when running the Turbo methods in the shell. They work fine within views. I believe this has something to do with the async_to_sync() method in Turbo._broadcast() and the warnings mentioned here: https://docs.djangoproject.com/en/3.2/topics/async/#asgiref.sync.sync_to_async

I tried a number of different approaches and still could not get it to work from the shell. As synchronous scripts should be able to send messages, any insights would be appreciated.

elamje commented 3 years ago

I don't have any insights on how to fix at the moment, but I'll dig deeper.

However, I did narrow down that I cannot get string named Broadcasts working. For instance, I created a similar chat app (no rooms), just a single model. Using a single model forced me to use a string hardcoded stream name. I should be able to add comments and stream the comments back to the UI, but the stream subscription isn't working for some reason. Things I know:

scuml commented 2 years ago

This is caused by the InMemoryChannelLayer in the CHANNEL_LAYERS setting. The memory is not shared between python processes.

To fix, use another channel layer. The only officially maintained one is channels_redis.

CHANNEL_LAYERS = {
    "default": {
        "BACKEND": "channels_redis.core.RedisChannelLayer",
        "CONFIG": {
            "hosts": [("localhost", 6379)],
        },
    }
}

https://channels.readthedocs.io/en/stable/topics/channel_layers.html