Serving Django Channels In Production-like Setting With Apache Directing Traffic

ぃ、小莉子 提交于 2019-12-06 00:35:03

I also struggled to get it run on my Raspberry, but finally I made it.

from https://mikesmithers.wordpress.com/2017/02/21/configuring-django-with-apache-on-a-raspberry-pi/ I got good advices.

Apache needs some further packages to serve pages from Django application.

sudo apt-get install apache2-dev
sudo apt-get install libapache2-mod-wsgi-py3

also MPM (Multi-Processing-Module) has to be set.

a2dismod mpm_prefork
a2enmod mpm_worker
service apache2 restart

create asgi.py example from Django channels docu

https://channels.readthedocs.io/en/latest/deploying.html#run-protocol-servers

In my case I also had to add sys path to my Project

"""
ASGI entrypoint. Configures Django and then runs the 
application
defined in the ASGI_APPLICATION setting.
"""

import os
import sys
import django
from channels.routing import get_default_application

sys.path.append("/home/pi/Dev/WeatherStation")
os.environ.setdefault("DJANGO_SETTINGS_MODULE", 
"WeatherStation.settings")
django.setup()
application = get_default_application()

Now Daphne should not complain

daphne -p 8001 WeatherStation.asgi:application

Configure ASGI and Daphne for websockets in Apache, use Apache for HTTP requests. Apache acts like a reverse proxy, redirecting all the websocket requests to Daphne server which is running on a different port

leafpad /etc/apache2/sites-available/000-default.conf

and the content

...
        RewriteEngine on
        RewriteCond %{HTTP:UPGRADE} ^WebSocket$ [NC,OR]
        RewriteCond %{HTTP:CONNECTION} ^Upgrade$ [NC]
        RewriteRule .* ws://127.0.0.1:8001%{REQUEST_URI} [P,QSA,L]


Alias /static /home/pi/Dev/WeatherStation/static
    <Directory /home/pi/Dev/WeatherStation/static> 
        Require all granted
    </Directory>

    <Directory /home/pi/Dev/WeatherStation/WeatherStation>
        <Files wsgi.py>
            Require all granted
        </Files>
    </Directory>

    WSGIDaemonProcess Dev python-path=/home/pi/Dev python-home=/home/pi/Dev/WSenv
    WSGIProcessGroup Dev
    WSGIScriptAlias / /home/pi/Dev/WeatherStation/WeatherStation/wsgi.py
</VirtualHost>

Make sure that Apache has access to your db and other stuff

chmod g+w ~/dvds/db.sqlite3
chmod g+w ~/dvds
sudo chown :www-data db.sqlite3
sudo chown :www-data ~/dvds

Restart Apache for these changes to take effect:

sudo service apache2 restart

Now you have a WSGI server running in Apache and a Daphne server for websockets

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!