我试图了解Django渠道中消费者的流向。
我写了下面的使用者,它对查询集进行一次小检查,并每分钟返回一个结果。
我已经能够与WebSocket建立连接,但是我不明白我以后如何开始使用它,再次,我需要它每60秒运行一次检查,因此以某种方式使用睡眠吗?
消费者:
class CameraOnlineConsumer(JsonWebsocketConsumer):
def connect(self):
self.farm_name = '1'
self.farm_group_name = 'farm_%s' % self.farm_name
# Join farm group
async_to_sync(self.channel_layer.group_add)(
self.farm_group_name,
self.channel_name
)
# TODO: Once working, add Auth
# accept connection
self.accept()
def camera(self, event):
result = self.check_events() # Get updated camera status
async_to_sync(self.channel_layer.group_send)(
self.farm_group_name, # send result to group
{
'type': 'check_events',
'message': result
}
)
@database_sync_to_async
def get_events(self):
return PastureEvent.objects.filter(result=8, farm_id=self.farm_name, processed=False).order_by('-time_stamp')[
:2]
@database_sync_to_async
def update_event(self, query_set):
PastureEvent.objects.select_for_update().filter(id=query_set[1].id).update(processed=True)
def check_events(self):
minute_delta = timedelta(seconds=60)
query_set = self.get_events()
if not query_set:
result = {'camera status': CameraOffline.default_detail, }
return result
elif len(query_set) == 1: # means that no new events has been recorded since last check.
result = {'camera status': CameraOnline.default_detail,
'first time_stamp': str(query_set[0].time_stamp)}
return result
elif len(query_set) >= 2: # two relevant events received.
difference = query_set[0].time_stamp - query_set[1].time_stamp
if difference <= minute_delta:
if query_set[1]:
# query_set[1].processed = True & query_set[1].save() didn't work, why?
self.update_event(query_set=query_set)
else:
pass
# time difference between them is under/equal to the desired time difference between events.
result = {'camera status': CameraOnline.default_detail,
'first time_stamp': str(query_set[0].time_stamp),
'last time_stamp': str(query_set[1].time_stamp)}
return result
else:
if query_set[1]:
self.update_event(query_set=query_set)
else:
pass
# two events exist but the difference between them is bigger then one minute, if changed in the next
# check it would be updated to camera online.
result = {'camera status': CameraOnline.default_detail,
'first time_stamp': str(query_set[0].time_stamp)}
return result
else:
# For now, every other case should result in a camera offline msg as well.
return {'camera status': CameraOffline.default_detail}
一个基本的JS使用者:
const ws = new WebSocket("ws://127.0.0.1:8000/ws/camera_online/connect/camera");
ws.onmessage = function(event) {
console.log(event.data);
};
ws.OPEN
返回1