2

Is it possible to run a daphne process or even just Django channels from a python script?

The recommended way to do it, is to run

daphne -b 0.0.0.0 -p 8001 django_project.asgi:channel_layer

I was wondering if I could bind that to a variable and run it the way Tornado could

from tornado.web import Application
application = Application([(r"/", RosbridgeWebSocket), (r"", RosbridgeWebSocket)])
cjds
  • 7,573
  • 9
  • 41
  • 75

3 Answers3

1

This is kind of a work around, but you may use the subprocess module like this:

subprocess.run(["daphne", "-b 0.0.0.0 -p 8001 django_project.asgi:channel_layer"])

Check this thread Calling an external command in Python for more info on the use of subprocess module.

John Moutafis
  • 18,296
  • 5
  • 55
  • 96
  • Yeah, I know that I can call it as a subprocess, but then unless I write a bunch of IPC code this wouldn't work – cjds Mar 06 '17 at 15:40
  • Have you considered creating a .sh bash script calling daphne as you would normally do from command line and call that script from the subprocess? – John Moutafis Mar 06 '17 at 16:48
  • That's the current way this works. I'd ideally have it as a python object though – cjds Mar 06 '17 at 17:15
  • In the subprocess documentation, states that it returns a CompletedProcess instance, so it is an object... – John Moutafis Mar 06 '17 at 22:49
1

I am not familiar with Django Channels but have you tried using inmemory or redis Channels directly? You might be able to avoid daphne altogether. From what I understand, daphne seems to be the protocol translator layer so outside clients can communicate with Django through daphne (Django uses wsgi rather than asgi so Django alone cannot handle certain protocols, such as, websocket communication). Tornado does not rely on wsgi.

There are examples in daphne tests: https://github.com/django/daphne/blob/master/daphne/tests/test_http.py

The inmemory ChannelLayer is not cross-process. I'm not sure if that even matters in your use case. If it does, you can check the other backends (such as redis channels) https://channels.readthedocs.io/en/stable/backends.html

This might be more directly what you are looking for: https://github.com/django/asgi_redis

Louis
  • 554
  • 3
  • 17
  • 1
    I just started reading about this last night. Indeed this looks like the object that I have to customize to run other python code with my Daphne. Still looking into it but here's hoping – cjds Mar 09 '17 at 17:31
0

have you tried it swap the tornado to NGINX ?

http://masnun.rocks/2016/11/02/deploying-django-channels-using-daphne/