我想用 django-channels 构建一个 Django 应用程序。 但是当我运行以下命令时:
daphne -b 0.0.0.0 -p 8010 paya.asgi:application
它给了我这个错误:应用程序尚未加载。 当我将以下行添加到 Consumer.py 时,会发生此错误:
from Auth.models import Store
consumers.py:
import json
from channels.generic.websocket import WebsocketConsumer
from asgiref.sync import async_to_sync
from Auth.models import Store
class ChatConsumer(WebsocketConsumer):
def connect(self):
self.user = self.scope['url_route']['kwargs']['sender']
self.store = self.scope['url_route']['kwargs']['receiver']
self.user_store_group = f'store_{self.user}_{self.store}'
async_to_sync(self.channel_layer.group_add)(
self.user_store_group,
self.channel_name
)
self.accept()
#self.sotreUser = Store.objects.get(id=self.store)
#data = [json.dumps({'name': 1, 'productId': 2, 'receiver': self.sotreUser.user.username})]
#self.send(text_data=data)
def disconnect(self, close_code):
async_to_sync(self.channel_layer.group_discard)(
self.room_group_name,
self.channel_name
)
def receive(self, text_data):
text_data_json = json.loads(text_data)
print(text_data)
async_to_sync(self.channel_layer.group_send)(
self.room_group_name,
{
'type': 'add_order',
'message': text_data_json
}
)
def add_order(self, event):
message = event['message']
self.send(text_data=json.dumps({
'message': message
}))
asgi.py:
import os
from channels.routing import ProtocolTypeRouter, URLRouter
from django.core.asgi import get_asgi_application
from channels.auth import AuthMiddlewareStack
from django.urls import path
from chat.consumers import *
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings')
application = ProtocolTypeRouter({
"http": get_asgi_application(),
"websocket": AuthMiddlewareStack(
URLRouter(
[path('ws/chat/<str:sender>/<str:receiver>/', ChatConsumer.as_asgi()),]
)
),
})
设置.py:
INSTALLED_APPS = [
'daphne',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'chat',
]
ASGI_APPLICATION = 'paya.asgi.application'
CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { "hosts": [('127.0.0.1', 6379)], }, },}
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'NAME',
'USER': 'USER',
'PASSWORD': 'PASSWORD',
'HOST': 'localhost',
'PORT': '',
}
}
这个命令:
sudo tail -f /var/log/daphne.err.log
提出了这个错误:
django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.
INSTALLED_APPS = [
'channels',
'daphne',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'chat',
]
你可以试试这个吗