Hello everyone,
I have a project where I need to receive data from a POST request, save it to the database and then send the database content to a websocket. This works completely fine when I use the django development server.
But as soon as I use a production environment (nginx, uwsgi and daphne) the data does not get sent to the websocket. Saving to the database works fine, it just does not get sent.
Also, when receiving over the websocket I can send without any problems in the production environment. It’s just the problem with receiving over a POST request and then sending to the websocket.
Why could that be? Here is my code:
views.py
from django.shortcuts import render
from django.template.loader import render_to_string
from asgiref.sync import async_to_sync
from channels.layers import get_channel_layer
from django.utils import timezone
from datetime import datetime
from .models import Loesung
def loesungsUpdate():
loesungen = Loesung.objects.all()
if loesungen:
for i in loesungen:
i.abgabezeit = datetime.fromisoformat(str(i.abgabezeit)).astimezone(timezone.get_current_timezone()).strftime("%d.%m.%Y, %H:%M")
loesungen = render_to_string('mathenacht/partials/loesungsuebersichtUpdate.html', {'loesungen':loesungen})
channel_layer = get_channel_layer()
async_to_sync(channel_layer.group_send)(
'loesungsuebersicht', {
'type': 'loesungsuebersichtUpdateHandler', # Handler must be in consumers.py
'loesungen': loesungen,
}
)
consumers.py
from channels.generic.websocket import WebsocketConsumer
from asgiref.sync import async_to_sync
from django.template.loader import render_to_string
from django.utils import timezone
from datetime import datetime
import json
from .models import Loesung
class mathenachtConsumer(WebsocketConsumer):
def connect(self):
async_to_sync(self.channel_layer.group_add)( # Add the connecting user to a 'backend' chatroom so that everyone receives every message
'loesungsuebersicht', self.channel_name # chatroom as a hardcoded name for the chatroom, self.channel_name gets auto filled from Django and is tied to the user
)
self.accept()
def disconnect(self, code):
async_to_sync(self.channel_layer.group_discard)( # Remove the user from that chatroom
'loesungsuebersicht', self.channel_name
)
def receive(self, text_data):
...
def loesungsuebersichtUpdateHandler(self, event):
self.send(text_data=event['loesungen'])
I removed the code from the receive function in consumers.py because it is long and not necessary for the problem (i think ).
I am happy to give more information if needed. Thanks in advance.