在 systemd 上使用 daphne 运行 django 频道

jhc*_*jhc 4 django nginx systemd django-channels daphne

首先,抱歉问了这么长的问题,我希望你们中的一些人对此有耐心。

TL; DR:如何在 systemd 中正确加载 django 设置?

我正在遵循本指南,使用 Daphne 部署 Django 频道,因此我可以运行一些实时应用程序(使用 WebSockets)。如果没有 nginx,并从命令行运行工作程序 (python manage.py runworker) 和接口 (daphne),我可以访问正确的频道使用者类,如下面的日志所示(这些是从 javascript 客户端触发的) :

2017-10-09 21:10:35,210 - DEBUG - worker - Got message on websocket.connect (reply daphne.response.CYeWgnNQoY!mwuQrazQtv)
2017-10-09 21:10:35,211 - DEBUG - runworker - websocket.connect
2017-10-09 21:10:35,211 - DEBUG - worker - Dispatching message on websocket.connect to api.consumers.OrderConsumer
2017-10-09 21:10:48,132 - DEBUG - worker - Got message on websocket.receive (reply daphne.response.CYeWgnNQoY!mwuQrazQtv)
2017-10-09 21:10:48,132 - DEBUG - runworker - websocket.receive
2017-10-09 21:10:48,132 - DEBUG - worker - Dispatching message on websocket.receive to api.consumers.OrderConsumer
Run Code Online (Sandbox Code Playgroud)

这些事件由以下 javascript 调用触发:

ws = new WebSocket("ws://localhost:8000/order/1/")
ws.send("test")
Run Code Online (Sandbox Code Playgroud)

使用 nginx 并在 systemd 上同时运行 interface 和 worker,尽管使用了完全相同的触发器输入,但我还是得到了以下日志。

2017-10-09 20:38:35,503 - DEBUG - worker - Got message on websocket.connect (reply daphne.response.PPGuXtBmQD!EgUfaNZjUj)
2017-10-09 20:38:35,503 - DEBUG - runworker - websocket.connect
2017-10-09 20:38:35,503 - DEBUG - worker - Dispatching message on websocket.connect to channels.routing.connect_consumer
2017-10-09 20:38:42,993 - DEBUG - worker - Got message on websocket.receive (reply daphne.response.PPGuXtBmQD!EgUfaNZjUj)
2017-10-09 20:38:42,993 - DEBUG - runworker - websocket.receive
2017-10-09 20:38:42,993 - DEBUG - worker - Dispatching message on websocket.receive to channels.routing.null_consumer
Run Code Online (Sandbox Code Playgroud)

请注意,接收通道被路由到null_consumer. 我相信这里的问题只是channels.routing没有设置好这一事实。由于我在两个版本中使用相同的设置(Django 设置文件),这可能意味着设置本身没有被正确加载。请考虑以下文件。

## rest-api/farmaApp/settings.py

...
CHANNEL_LAYERS = {
    'default': {
        'BACKEND': 'asgi_redis.RedisChannelLayer',
        'CONFIG': {
            'hosts': [('localhost', 6379)],
        },
        'ROUTING': 'farmaApp.routing.channel_routing',
    }
}
...
Run Code Online (Sandbox Code Playgroud)

应该设置channels.routing为:

## rest-api/farmaApp/routing.py

from channels.routing import route
from api.consumers import ws_connect, ws_disconnect, OrderConsumer

channel_routing = [
    route('websocket.connect', ws_connect, path=r'^/users/'),
    route('websocket.disconnect', ws_disconnect, path=r'^/users/'),
    OrderConsumer.as_route(path=r'^/order/(?P<order_id>[\d+])/'),
]
Run Code Online (Sandbox Code Playgroud)

同样,我不认为配置本身是错误的,因为它可以在没有 systemd 的情况下工作。最后,这是我的 systemd 配置:

## /etc/systemd/system/daphne.service

[Unit]
Description=daphne daemon
After=network.target

[Service]
User=ubuntu
Group=www-data
WorkingDirectory=/home/ubuntu/rest-api
Environment=DJANGO_SETTINGS_MODULE=farmaApp.settings
ExecStart=/home/ubuntu/rest-api/env/bin/daphne --access-log /home/ubuntu/rest-api/access.log -b 0.0.0.0 -p 8001 farmaApp.asgi:channel_layer

[Install]
WantedBy=multi-user.target


## /etc/systemd/system/django_worker.service
[Unit]
Description=django_worker daemon
After=network.target

[Service]
User=ubuntu
Group=www-data
WorkingDirectory=/home/ubuntu/rest-api
Environment=DJANGO_SETTINGS_MODULE=farmaApp.settings
ExecStart=/home/ubuntu/rest-api/env/bin/python manage.py runworker -v 2

[Install]
WantedBy=multi-user.target
Run Code Online (Sandbox Code Playgroud)

请注意我根据链接指南导出到环境中的 DJANGO_SETTINGS_MODULE 变量的两个配置文件。我相信这不会按预期工作。

小智 5

我刚刚部署了我的 django 频道应用程序,以下 systemd 服务文件对我有用,而无需使用主管:

/etc/systemd/system/django-channels-daphne.service

[Unit]
Description=daphne server script for my project
After=network.target

[Service]
User=webuser
Group=webuser
WorkingDirectory=/path/to/myproject
Environment=DJANGO_SECRET_KEY=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
Environment=DJANGO_ALLOWED_HOSTS=myapp.chatbot.ai
ExecStart=/path/to/python/virtualenv/bin/daphne -b 0.0.0.0 -p 8000 myproject.asgi:channel_layer
Restart=always

[Install]
WantedBy=multi-user.target
Run Code Online (Sandbox Code Playgroud)

/etc/systemd/system/django-channels-runworker.service

[Unit]
Description=python runworker server for myproject
After=network.target

[Service]
User=webuser
Group=webuser
WorkingDirectory=/path/to/myproject
Environment=DJANGO_SECRET_KEY=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
Environment=DJANGO_ALLOWED_HOSTS=myapp.chatbot.ai
ExecStart=/path/to/python/virtualenv/bin/python /path/to/myproject/manage.py runworker --threads 4 
Restart=always

[Install]
WantedBy=multi-user.target
Run Code Online (Sandbox Code Playgroud)

/path/to/myproject/myproject/asgi.py

import os
import channels

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myproject.settings")
channel_layer = channels.asgi.get_channel_layer()
Run Code Online (Sandbox Code Playgroud)

/path/to/myproject/myproject/settings.py 中的一些行:

ALLOWED_HOSTS = [os.environ['DJANGO_ALLOWED_HOSTS']]
SECRET_KEY = os.environ['DJANGO_SECRET_KEY']
Run Code Online (Sandbox Code Playgroud)

  • 将 DJANGO_SECRET_KEY 和 DJANGO_ALLOWED_HOSTS 放在 daphne.service 文件中的目的是什么? (3认同)

AMG*_*AMG 0

是的,supervisord 确实起作用了。/etc/supervisor/conf.d/project_name.conf 的关键部分是(注释部分中的一些进一步链接):

[program:platform_asgi_daphne]
; # /sf/ask/1193916601/
; # https://github.com/django/daphne/pull/37
; # https://wiki.cac.washington.edu/display/infra/Extracting+Certificate+and+Private+Key+Files+from+a+.pfx+File
; # daphne -e ssl:8443:privateKey=localhost.key:certKey=localhost.crt <channel_layer>
environment =
    DJANGO_SECRET_KEY='xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
    DJANGO_DEBUG='True'
directory=/path/to/project/
; # http://channels.readthedocs.io/en/stable/deploying.html
; command=/path/to/venv/bin/daphne --port 80 --bind 0.0.0.0 classact.asgi:channel_layer
command=/path/to/venv/bin/daphne -e ssl:443:privateKey=../keys/server.key:certKey=../keys/server.crt --bind 0.0.0.0 projectfoldername.asgi:channel_layer
;user=webapps
;group=webapps
user=root
group=webapps

[program:platform_asgi_workers]
; # https://github.com/django/channels/issues/408#issuecomment-276384104
environment =
    DJANGO_SECRET_KEY='xxxxxxxxxxxxxxxxxxxxxxxxx',
    DJANGO_DEBUG='True'
command=/path/to/venv/bin/python /path/to/project/manage.py runworker
process_name=asgi_worker%(process_num)s
numprocs=2
;user=webapps
user=root
group=webapps
Run Code Online (Sandbox Code Playgroud)

我在作为用户 webapp 运行时遇到了一些问题,这些问题尚未解决,因此它们以 root 身份运行(写入具有奇数权限的加密文件夹)。我还没有达到在每个部分中不重复一堆环境变量的程度(可能有办法)。还有其他几个,如数据库、用户、静态根等,具体取决于平台(产品或开发)。

我还有一些证书需要处理,以便也显示出来(如果不需要,请取出 ssl 部分)。另请注意运行两个工人。