Take a look at this example.
As you can see, some sort of event
is constantly being sent to the client. I want to imitate this using Django-Channels
, inside consumers.py
. Here's a simplified version of what I have:
class ChatConsumer(AsyncConsumer):
async def ws_connect(self, event):
self.send = get_db_object()
....
await self.send({
"type": "websocket.accept"
})
# I need to CONSTANTLY receive & send data
async def ws_receive(self, event):
obj = ...# query DB and get the newest object
json_obj = {
'field_1': obj.field_1,
'field_2': obj.field_2,
}
await self.send({
"type": "websocket.send",
"text": json.dumps(json_obj)
})
@database_sync_to_async
def get_db_object(self, **kwargs):
return Some_Model.objects.get(**kwargs)[0]
Here, I want my Django backend to constantly:
- Query DB
- Receive obj from DB
- Send the received obj to Front-End WebSocket as
event
How can I achieve this? The important thing is that I need to CONSTANTLY send data to the client.
Most of the Django-Channels
resources on the internet cover only Chat Apps, which don't necessarily constantly send data to the client. I couldn't find any working code that does this job.
Please, no more recommendation for Redis or channels documentation... or some random 3rd party libraries that lacks good documentation... It's easy to recommend but hard to implement. For example, I found someone recommending Snorky
, but it really lacks documentation on how to implement it.
However, if there's a website that specifically does this job, I might take a look at it, even if it doesn't use Django-Channels.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…