def send_message(self, message): if not self.chat: AsyncToSync(self.send_json)({'error': 'NO_CHAT_JOINED'}) else: try: blacklist_validator(message) Messages.objects.send_message(sender=self.scope['user'], receiver_id=self.chat, message=message) except ValidationError: AsyncToSync(self.send_json)({'error': 'BLACKLISTED_MESSAGE'})
def notify_user_error(puser, msg): user = User.objects.get(pk=puser) result = {"type": "user.error", "error": msg} # Channel back to Consumer channel = get_channel_layer() AsyncToSync(channel.group_send)(user.username, result)
def test(self): console = Console() for i, (model_key, item, expected, keyword_args) in enumerate( self._iterate_test_cases(model_key=self.configuration_key) ): result = None try: if isinstance(self, AsyncModel): result = AsyncToSync(self.predict)(item, **keyword_args) else: result = self.predict(item, **keyword_args) assert result == expected console.print(f"[green]TEST {i+1}: SUCCESS[/green]") except AssertionError: console.print( "[red]TEST {}: FAILED[/red]{} test failed on item".format( i + 1, " [" + model_key + "]" if model_key else "" ) ) t = Tree("item") console.print(describe(item, t=t)) t = Tree("expected") console.print(describe(expected, t=t)) t = Tree("result") console.print(describe(result, t=t)) raise
def connect(self): if self.is_authenticated(): AsyncToSync(self.channel_layer.group_add)(self.group_name(), self.channel_name) self.accept() else: pass
def _predict(self, item, **kwargs): # The following does not currently work, because AsyncToSync does not # seem to correctly wrap asynchronous generators for r in AsyncToSync(self.model_dependencies["async_model"]. async_model.predict_gen)(iter((item, ))): break return r
def actionlog_notify_consumer(sender, instance, created, **kwargs): if created: slug = instance.tournament.slug group_name = ActionLogEntryConsumer.group_prefix + "_" + slug AsyncToSync(get_channel_layer().group_send)(group_name, { "type": "broadcast", "data": instance.serialize, })
def broadcast(instance, created): slug = instance.tournament.slug group_name = CheckInEventConsumer.group_prefix + "_" + slug payload = instance.serialize() payload['created'] = created AsyncToSync(get_channel_layer().group_send)(group_name, { "type": "broadcast", "data": payload })
def send_asset_reservation_message(*, sender, message_type, asset_pk, user_pk): AsyncToSync(ASSET_CHANNEL_LAYER.group_send)( "asset_updates", { "type": message_type, "asset_pk": asset_pk, "user_pk": user_pk }, )
async def __call__(self, receive, send): # Alright, wait for the http.request message message = await receive() if message["type"] != "http.request": raise ValueError("WSGI wrapper received a non-HTTP-request message") # Wrap send so it can be called from the subthread self.sync_send = AsyncToSync(send) # Call the WSGI app await self.run_wsgi_app(message)
def save(self): # 1. Unconfirm the other, if necessary if self.cleaned_data['confirmed']: if self.debate.confirmed_ballot != self.ballotsub and self.debate.confirmed_ballot is not None: self.debate.confirmed_ballot.confirmed = False self.debate.confirmed_ballot.save() # 2. Save ballot submission so that we can create related objects if self.ballotsub.pk is None: self.ballotsub.save() # 3. Save the specifics of the ballot self.save_ballot() # 4. Save ballot and result status self.ballotsub.discarded = self.cleaned_data['discarded'] self.ballotsub.confirmed = self.cleaned_data['confirmed'] self.ballotsub.save() self.debate.result_status = self.cleaned_data['debate_result_status'] self.debate.save() # 5. Notify the websocket Latest Results consumer if result is 'final' if self.ballotsub.confirmed: if self.debate.result_status is self.debate.STATUS_CONFIRMED: slug = self.debate.round.tournament.slug group_name = BallotResultConsumer.group_prefix + "_" + slug AsyncToSync(get_channel_layer().group_send)(group_name, { "type": "broadcast", "data": self.ballotsub.serialize_like_actionlog }) # 6. Notify the websocket Ballots Status if result is for current round if self.debate.round == self.debate.round.tournament.current_round: slug = self.debate.round.tournament.slug group_name = BallotStatusConsumer.group_prefix + "_" + slug AsyncToSync(get_channel_layer().group_send)(group_name, { "type": "broadcast", "data": BallotStatusConsumer.get_data(self.debate.round) }) return self.ballotsub
def startacquisition(self): AsyncToSync(self.channel_layer.group_send)( self.hostname, { 'id': self.chromatogram.pk, 'baudrate': self.baudrate, 'port': self.portname, 'samplerate': self.chromatogram.SampleRate, 'rheodyneswitch': self.chromatogram.RheodyneSwitch, 'type': 'hplc.startMeasurement' })
def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] AsyncToSync(self.channel_layer.group_send)( self._chat_channel_name, { 'type': 'chat_message', 'message': message })
def send_asset_reservation_message(*, sender, message_type, asset_pk, reservation_token): AsyncToSync(ASSET_CHANNEL_LAYER.group_send)( "asset_updates", { "type": message_type, "asset_pk": asset_pk, "reservation_token": reservation_token, "sent": time(), }, )
def create(self, validated_data): room = validated_data['room'] content = validated_data['content'] channel_layer = get_channel_layer() group_send = AsyncToSync(channel_layer.group_send) group_send(room, { 'type': 'chat.message', 'text': content }) return to_object(validated_data)
def send_to_broadcast(user, cmd="notify", kwargs={}): ## Send realtime notify to all AsyncToSync(channel_layer.group_send)("broadcast", dict( type="send.all", text=json.dumps(dict( sender=user.username if user else "system", role=user.is_staff if user else False, status=user.is_active if user else False, cmd=cmd, **kwargs, )) ))
def get_active_channels(): group_name = 'channels_group' channel_layer = get_channel_layer() try: active_channels = requests.get( 'http://192.168.7.110 :8088/ari/channels', auth=HTTPBasicAuth('roip_ari', 'roip_ari')).text channels_dict = { 'group_name': group_name, 'celery_response': True, 'data': active_channels } AsyncToSync(channel_layer.group_send)(group_name, { 'type': 'send.celery', 'message': channels_dict }) except ConnectionError: AsyncToSync(channel_layer.group_send)( group_name, { 'type': 'send.message', 'message': 'Blad polaczenia z Asteriskiem' })
def bridges_connection_info(): response_list = [] group_name = 'bridges_connection_info_group' channel_layer = get_channel_layer() try: bridges_list = json.loads( requests.get('http://192.168.7.110:8088/ari/bridges', auth=HTTPBasicAuth('roip_ari', 'roip_ari')).text) print(bridges_list) channels_list = json.loads( requests.get('http://192.168.7.110:8088/ari/channels', auth=HTTPBasicAuth('roip_ari', 'roip_ari')).text) for bridge in bridges_list: itter = 0 bridge_dict = { 'id': bridge.get('id'), 'creator': bridge.get('creator'), 'name': bridge.get('name'), 'ari': bridge, 'channels_list': [] } active_channels = bridge.get('channels') for channel in active_channels: for api_channel in channels_list: if api_channel.get('id') == channel: itter += 1 bridge_dict.get('channels_list').append(api_channel) bridge_dict.update({'channels_count': itter}) response_list.append(bridge_dict) AsyncToSync(channel_layer.group_send)(group_name, { 'type': 'send.celery', 'message': response_list }) except ConnectionError: AsyncToSync(channel_layer.group_send)( group_name, { 'type': 'send.message', 'message': 'Blad polaczenia z Asteriskiem' })
def send_to_session(caller, callee, cmd="notify", kwargs={}): ## Send realtime notify to specific callee session_group_name = "session_%s" % get_channel_group_name(user=callee) AsyncToSync(channel_layer.group_send)(session_group_name, dict( type="data_handller", data=json.dumps(dict( sender=caller.username if caller else "system", role=caller.is_staff if caller else False, status=caller.is_active if caller else False, cmd=cmd, **kwargs, )) ))
def notify_group(group, message): """ Dumps the message to JSON and sends it to the specified channel. :param group: str :param message: dict """ channel_layer = get_channel_layer() payload = json.dumps(camelize(message)) return AsyncToSync(channel_layer.group_send)(group, { "type": "notification.message", "text": payload })
def get_active_channels(): group_name = 'channels_group' channel_layer = get_channel_layer() active_channels = requests.get('http://192.168.7.17:8088/ari/channels', auth=HTTPBasicAuth('roip_ari', 'roip_ari')).text channels_dict = { 'group_name': group_name, 'celery_response': True, 'data': active_channels } AsyncToSync(channel_layer.group_send)(group_name, { 'type': 'send.celery', 'message': channels_dict })
def get_user_processes(puser): user = User.objects.get(pk=puser) processes = UserProcess.objects.filter(user=user) processes = [d.process for d in processes] if len(processes) == 0: processes = list() result = { "type": "process.respond", "processes": serializers.serialize('json', processes) } # Channel back to Consumer channel = get_channel_layer() AsyncToSync(channel.group_send)(user.username, result)
def connect(self): self.user = self.scope["user"] self.joined_channels = [] if self.check_anonymous(): return self.accept() logger.debug("New User Connection: %s (%s)", self.channel_name, self.user) user_channel_name = self.user.unique_name() AsyncToSync(self.channel_layer.group_add)(user_channel_name, self.channel_name) self.joined_channels = [user_channel_name] logger.info("New User Connection %s joined %s (%s)", self.user, self.joined_channels, self.channel_name) self.user_message({"data": json.dumps({"connected": True})})
async def __call__(self, scope, receive, send): if scope["type"] != "http": raise ValueError("WSGI wrapper received a non-HTTP scope") self.scope = scope with SpooledTemporaryFile(max_size=65536) as body: # Alright, wait for the http.request messages while True: message = await receive() if message["type"] != "http.request": raise ValueError("WSGI wrapper received a non-HTTP-request message") body.write(message.get("body", b"")) if not message.get("more_body"): break body.seek(0) # Wrap send so it can be called from the subthread self.sync_send = AsyncToSync(send) # Call the WSGI app await self.run_wsgi_app(body)
def SetDeadTime(request, chromatogramid, DeadTime): if request.user and request.user.is_authenticated and request.user.has_perm( 'chromatogram.chromatogram_edit'): c = Chromatogram.objects.get(pk=chromatogramid) c.DeadTime = DeadTime c.save() channel_layer = get_channel_layer() AsyncToSync(channel_layer.group_send)("ChromatogramDetails_%s" % c.id, { 'message': { 'DeadTime': DeadTime }, 'type': 'hplc.setDeadTime' }) return HttpResponse() else: return HttpResponse(status=401)
def send_asset_update(*, instance, **kwargs): latest_trans = None latest_transcription = instance.transcription_set.order_by("-pk").first() if latest_transcription: latest_trans = { "text": latest_transcription.text, "id": latest_transcription.pk, "submitted_by": latest_transcription.user.pk, } AsyncToSync(ASSET_CHANNEL_LAYER.group_send)( "asset_updates", { "type": "asset_update", "asset_pk": instance.pk, "status": instance.transcription_status, "difficulty": instance.difficulty, "latest_transcription": latest_trans, }, )
def async_send(channel_name, job): """Send job message to front-end. uses the channel_name and Job object. Send success or failure status. Args: channel_name (object): websocket channel name job (object): model object of the job """ channel_layer = get_channel_layer() AsyncToSync(channel_layer.send)(channel_name, { "type": "celery.message", "text": json.dumps({ "action": "check status", "job_id": job.id, "job_name": job.name, "job_status": job.status, }) })
def __main_loop(self): buffer = '' currentdatetime = 0 zyklusAlt = 1 tmpList = [] while self.stopacquisitionflag == False: inbuff = self.serialInterface.inWaiting() # ab hier python3 fix, da sonst zu schnell daten gelesen werden und inWaiting immer 0 zurück gibt if inbuff == 0: time.sleep(0.33) # ende python3 fix while '\n' not in buffer: buffer = buffer + self.serialInterface.read(1).decode("utf-8") if '\n' in buffer: # genau dann ist eine Messreihe übertragen zyklus, zeitInMin,uv, counts = buffer.split(',', 3) if (int(zyklus) < int(zyklusAlt)): zyklusAlt = 1 self.runNumber = self.runNumber + 1 previd = self.chromatogram.pk self.chromatogram.pk = None self.chromatogram.Comment = self.chromatogram.Comment.split('|')[0] + "|Run:" + str(self.runNumber) self.chromatogram.Datetime = datetime.datetime.now().timestamp() currentdatetime = 0 self.chromatogram.save() prev = Chromatogram.objects.get(pk=previd) prev.NextChromatogram = self.chromatogram.pk prev.save() if self.prefixChannelName: self.dataCache = {self.prefix + "Counter": [], self.prefix + "UV": []} else: self.dataCache = {"Counter": [], "UV": []} zyklusAlt = int(zyklus) # do db save here data1 = HplcData() data1.Chromatogram = self.chromatogram data1.Value = counts data1.Datetime = currentdatetime data1.ChannelName = "Counter" if self.prefixChannelName: data1.ChannelName = self.prefix+data1.ChannelName tmpList.append(data1) AsyncToSync(self.channel_layer.group_send)("ChromatogramDetails_%s" % self.chromatogram.id,{ 'message': model_to_dict(data1), 'type': 'hplc.data' }) self.dataCache[data1.ChannelName].append(model_to_dict(data1)) data2 = HplcData() data2.Chromatogram = self.chromatogram data2.Value = uv data2.Datetime = currentdatetime data2.ChannelName = "UV" if self.prefixChannelName: data2.ChannelName = self.prefix + data2.ChannelName tmpList.append(data2) AsyncToSync(self.channel_layer.group_send)("ChromatogramDetails_%s" % self.chromatogram.id, { 'message': model_to_dict(data2), 'type': 'hplc.data' }) self.dataCache[data1.ChannelName].append(model_to_dict(data2)) buffer = '' currentdatetime += 1 # so we dont lock the db too long # insert the first 10 values directly so we can show a graph that will refresh itself afterwards if len(tmpList) >= 10 or int(zyklus) < 10: HplcData.objects.bulk_create(tmpList) tmpList = [] if self.chromatogram.MaxRuntime != 0 and int(zyklus) / ( 60.0 * self.chromatogram.SampleRate) > self.chromatogram.MaxRuntime: # not using import here to not have cyclic references, as these tend to cause problems JuHPLC.SerialCommunication.\ MicroControllerManager.MicroControllerManager.\ getinstance().stopacquisitionforchromatogram(self.chromatogram) # persist data at the end HplcData.objects.bulk_create(tmpList)
def disconnect(self, message): AsyncToSync(self.channel_layer.group_discard)(self.group_name(), self.channel_name) # print('Channels: disconnect from', self.channel_name, self.group_name()) super().disconnect(message)
def connect(self): AsyncToSync(self.channel_layer.group_add)( self._chat_channel_name, self.channel_name) self.accept()
def disconnect(self, close_code): AsyncToSync(self.channel_layer.group_discard)( self._chat_channel_name, self.channel_name)