Python源码示例:channels.Group()

示例1
def delete_substage(request, id):
    try:
        sub_stage = Stage.objects.get(pk=id)
        old_fsxf = sub_stage.stage_forms
        old_fsxf.is_deleted = True
        # old_fsxf.stage = None
        old_fsxf.save()
        # org = sub_stage.stage.project.organization if sub_stage.stage.project else sub_stage.stage.site.project.organization
        # desc = "deleted form of stage {} substage {} by {}".format(sub_stage.stage.name, sub_stage.name,
        #                                                            request.user.username)
        # noti = old_fsxf.logs.create(source=request.user, type=1, title="form Deleted",
        #         organization=org, description=desc)
        # result = {}
        # result['description'] = desc
        # result['url'] = noti.get_absolute_url()
        # ChannelGroup("notify-{}".format(org.id)).send({"text": json.dumps(result)})
        # ChannelGroup("notify-0").send({"text": json.dumps(result)})
        # sub_stage.delete()
        return Response({}, status=status.HTTP_200_OK)
    except Exception as e:
        return Response({'error':e.message}, status=status.HTTP_400_BAD_REQUEST) 
示例2
def register(self, request, form, *args, **kwargs):
        with transaction.atomic():
            new_user = super(CreateUserView, self).register(
                request, form, *args, **kwargs)
            is_active = form.cleaned_data['is_active']
            new_user.first_name = request.POST.get('name', '')
            new_user.is_active = is_active
            new_user.is_superuser = True
            new_user.save()
            organization = int(form.cleaned_data['organization'])
            org = Organization.objects.get(pk=organization)
            profile = UserProfile(user=new_user, organization=org)
            profile.save()
            # noti = profile.logs.create(source=self.request.user, type=0, title="new User",
            #                         organization=profile.organization, description="new user {0} created by {1}".
            #                         format(new_user.username, self.request.user.username))
            # result = {}
            # result['description'] = 'new user {0} created by {1}'.format(new_user.username, self.request.user.username)
            # result['url'] = noti.get_absolute_url()
            # ChannelGroup("notify-{}".format(profile.organization.id)).send({"text":json.dumps(result)})
            # ChannelGroup("notify-0").send({"text":json.dumps(result)})

        return new_user 
示例3
def handle(self, *args, **options):
        result = {
            "id": 45639,
            "source_uid": 147,
            "source_name": "Kiran Shrestha",
            "source_img": "/media/logo/default_user.png",
            "get_source_url": "/users/profile/147/",
            "get_event_name": "staged form Ring Beam",
            "get_event_url": "/forms/forms/31523",
            "get_extraobj_name": "TestHouse",
            "get_extraobj_url": "/fieldsight/site-dashboard/4119/",
            "get_absolute_url": "/events/notification/45639/",
            "extra_json": '',
            "type": 16,
            "title": "new Site level Submission",
            "date": "2018-07-17T11:13:41.440880Z",
            "extra_message": '',
            "recipient": '',
            "seen_by": []
        },
        # ChannelGroup("notify-{}".format(1)).send({"text": json.dumps(result)})
        ChannelGroup("user-notify-{}".format(1)).send({"text": json.dumps(result)})
        ChannelGroup("org-notify-{}".format(1)).send({"text": json.dumps(result)})
        ChannelGroup("project-notify-{}".format(1)).send({"text": json.dumps(result)})
        self.stdout.write('Successfully created Notification') 
示例4
def sendNotification(notification, recipient):
    result={}
    result['id']= noti.id,
    result['source_uid']= source_user.id,
    result['source_name']= source_user.username,
    result['source_img']= source_user.user_profile.profile_picture.url,
    result['get_source_url']= noti.get_source_url(),
    result['get_event_name']= project.name,
    result['get_event_url']= noti.get_event_url(),
    result['get_extraobj_name']= None,
    result['get_extraobj_url']= None,
    result['get_absolute_url']= noti.get_absolute_url(),
    result['type']= 412,
    result['date']= str(noti.date),
    result['extra_message']= str(count) + " Sites @error " + u'{}'.format(e.message),
    result['seen_by']= [],
    ChannelGroup("notif-user-{}".format(recipient.id)).send({"text": json.dumps(result)}) 
示例5
def notify_subscribers(notifications, key):
    """
    Notify all open channels about new notifications
    """

    logger.debug("Broadcasting to subscribers")

    notification_type_ids = models.NotificationType.objects.values('key').filter(key=key)

    for notification_type in notification_type_ids:
        g = Group(
            settings.NOTIFICATION_CHANNEL.format(
                notification_key=notification_type['key']
            )
        )
        g.send(
            {'text': 'new-notification'}
        ) 
示例6
def notify_subscribers(notifications, key):
    """
    Notify all open channels about new notifications
    """

    logger.debug("Broadcasting to subscribers")

    notification_type_ids = models.NotificationType.objects.values('key').filter(key=key)

    for notification_type in notification_type_ids:
        g = Group(
            settings.NOTIFICATION_CHANNEL.format(
                notification_key=notification_type['key']
            )
        )
        g.send(
            {'text': 'new-notification'}
        ) 
示例7
def delete_mainstage(request, id):
    try:
        with transaction.atomic():
            stage = Stage.objects.get(pk=id)
            org = stage.site.project.organization if stage.site else stage.project.organization
            substages = Stage.objects.filter(stage=stage)
            for sub_stage in substages:
                if hasattr(sub_stage, 'stage_forms'):
                    old_fsxf = sub_stage.stage_forms
                    old_fsxf.is_deleted = True
                    old_fsxf.stage = None
                    old_fsxf.save()
                    # desc = "deleted form of stage {} substage {} by {}".format(sub_stage.stage.name, sub_stage.name,
                    #                                                            request.user.username)
                    # noti = old_fsxf.logs.create(source=request.user, type=1, title="form Deleted",
                    #         organization=org, description=desc)
                    # result = {}
                    # result['description'] = desc
                    # result['url'] = noti.get_absolute_url()
                    # ChannelGroup("notify-{}".format(org.id)).send({"text": json.dumps(result)})
                    # ChannelGroup("notify-0").send({"text": json.dumps(result)})
                sub_stage.delete()
            stage.delete()
        return Response({}, status=status.HTTP_200_OK)
    except Exception as e:
        return Response({'error':e.message}, status=status.HTTP_400_BAD_REQUEST) 
示例8
def all_notification(user, message):
        ChannelGroup("%s" % user).send({
            "text": json.dumps({
                "msg": message
            })
        }) 
示例9
def form_valid(self, form):
        self.object = form.save()
        noti = self.object.logs.create(source=self.request.user, type=6, title="new Role",
                                       organization=self.object.role.organization,
                                       description="new role {0} updated by {1}".
                                       format(self.object.name, self.request.user.username))
        result = {}
        result['description'] = 'new role {0} update by {1}'.format(self.object.name, self.request.user.username)
        result['url'] = noti.get_absolute_url()
        ChannelGroup("notify-{}".format(self.object.organization.id)).send({"text": json.dumps(result)})
        ChannelGroup("notify-0").send({"text": json.dumps(result)})

        return HttpResponseRedirect(self.get_success_url()) 
示例10
def delete(self,*args, **kwargs):
        self.object = self.get_object()
        noti = self.object.logs.create(source=self.request.user, type=6, title="new Site",
                                       organization=self.object.project.organization,
                                       description="new role {0} deleted by {1}".
                                       format(self.object.name, self.request.user.username))
        result = {}

        result['description'] = 'new role {0} deleted by {1}'.format(self.object.name, self.request.user.username)

        result['url'] = noti.get_absolute_url()
        ChannelGroup("notify-{}".format(self.object.project.organization.id)).send({"text": json.dumps(result)})
        ChannelGroup("notify-0").send({"text": json.dumps(result)})
        return HttpResponseRedirect(self.get_success_url()) 
示例11
def form_valid(self, form):
        self.object = form.save()
        noti = self.object.logs.create(source=self.request.user, type=9, title="new Organization",
                                       organization=self.object, content_object=self.object,
                                       description="{0} created a new organization named {1}".
                                       format(self.request.user, self.object.name))
        # result = {}
        # result['description'] = '{0} created a new organization named {1} '.format(noti.source.get_full_name(), self.object.name)
        # result['url'] = noti.get_absolute_url()
        # ChannelGroup("notify-{}".format(self.object.id)).send({"text": json.dumps(result)})
        # ChannelGroup("notify-0").send({"text": json.dumps(result)})

        return HttpResponseRedirect(self.get_success_url()) 
示例12
def form_valid(self, form):
        self.object = form.save()
        noti = self.object.logs.create(source=self.request.user, type=13, title="edit Organization",
                                       organization=self.object, content_object=self.object,
                                       description="{0} changed the details of organization named {1}".
                                       format(self.request.user.get_full_name(), self.object.name))
        # result = {}
        # result['description'] = noti.description
        # result['url'] = noti.get_absolute_url()
        # ChannelGroup("notify-{0}".format(self.object.id)).send({"text": json.dumps(result)})
        # ChannelGroup("notify-0").send({"text": json.dumps(result)})

        return HttpResponseRedirect(self.get_success_url()) 
示例13
def form_valid(self, form):
        self.object = form.save(organization_id=self.kwargs.get('pk'), new=True)
        
        noti = self.object.logs.create(source=self.request.user, type=10, title="new Project",
                                       organization=self.object.organization, content_object=self.object,
                                       description='{0} created new project named {1}'.format(
                                           self.request.user.get_full_name(), self.object.name))
        # result = {}
        # result['description'] = noti.description
        # result['url'] = noti.get_absolute_url()
        # ChannelGroup("notify-{}".format(self.object.organization.id)).send({"text": json.dumps(result)})
        # ChannelGroup("notify-0").send({"text": json.dumps(result)})


        return HttpResponseRedirect(self.object.get_absolute_url()) 
示例14
def form_valid(self, form):
        self.object = form.save(project_id=self.kwargs.get('pk'), new=True)
        noti = self.object.logs.create(source=self.request.user, type=11, title="new Site",
                                       organization=self.object.project.organization,
                                       project=self.object.project, content_object=self.object, extra_object=self.object.project,
                                       description='{0} created a new site named {1} in {2}'.format(self.request.user.get_full_name(),
                                                                                 self.object.name, self.object.project.name))
        # result = {}
        # result['description'] = '{0} created a new site named {1} in {2}'.format(self.request.user.get_full_name(),
        #                                                                          self.object.name, self.object.project.name)
        # result['url'] = noti.get_absolute_url()
        # ChannelGroup("project-{}".format(self.object.project.id)).send({"text": json.dumps(result)})
        # ChannelGroup("notify-0").send({"text": json.dumps(result)})

        return HttpResponseRedirect(self.get_success_url()) 
示例15
def form_valid(self, form):
        site = Site.objects.get(pk=self.kwargs.get('pk'))
        old_meta = site.site_meta_attributes_ans

        self.object = form.save(project_id=self.kwargs.get('pk'), new=False)
        new_meta = json.loads(self.object.site_meta_attributes_ans)

        extra_json = None
        if old_meta != new_meta:
            updated = {}
            meta_questions = site.project.site_meta_attributes
            for question in meta_questions:
                key = question['question_name']
                label = question['question_text']
                if old_meta.get(key) != new_meta.get(key):
                    updated[key] = {'label': label, 'data':[old_meta.get(key, 'null'), new_meta.get(key, 'null')]}
            extra_json = updated

        description = '{0} changed the details of site named {1}'.format(
            self.request.user.get_full_name(), self.object.name
        )

        noti = self.object.logs.create(
            source=self.request.user, type=15, title="edit Site",
            organization=self.object.project.organization,
            project=self.object.project, content_object=self.object,
            description=description,
            extra_json=extra_json,
        )
        # result = {}
        # result['description'] = 'new site {0} updated by {1}'.format(self.object.name, self.request.user.username)
        # result['url'] = noti.get_absolute_url()
        # ChannelGroup("notify-{}".format(self.object.project.organization.id)).send({"text": json.dumps(result)})
        # ChannelGroup("project-{}".format(self.object.project.id)).send({"text": json.dumps(result)})
        # ChannelGroup("site-{}".format(self.object.id)).send({"text": json.dumps(result)})
        # ChannelGroup("notify-0").send({"text": json.dumps(result)})

        return HttpResponseRedirect(self.get_success_url()) 
示例16
def get(self, *args, **kwargs):
        site = get_object_or_404(Site, pk=self.kwargs.get('pk'), is_active=True)
        site.is_active = False
        site.save()
        task_obj=CeleryTaskProgress.objects.create(user=self.request.user, description="Removal of UserRoles After Site delete", task_type=7, content_object = site)
        if task_obj:
            task = UnassignAllSiteRoles.delay(task_obj.id, site.id)
            task_obj.task_id = task.id
            task_obj.save()
        
        noti = task_obj.logs.create(source=self.request.user, type=36, title="Delete Site",
                               organization=site.project.organization, extra_object=site.project,
                               project=site.project, extra_message="site", site=site, content_object=site,
                               description='{0} deleted of site named {1}'.format(
                                   self.request.user.get_full_name(), site.name))
        return HttpResponseRedirect(reverse('fieldsight:proj-site-list', kwargs={'pk': site.project_id}))

    # def delete(self,*args, **kwargs):
    #     self.kwargs['pk'] = self.get_object().pk
    #     self.object = self.get_object().delete()
    #     # noti = self.object.logs.create(source=self.request.user, type=4, title="new Site",
    #     #                                organization=self.object.organization,
    #     #                                description="new project {0} deleted by {1}".
    #     #                                format(self.object.name, self.request.user.username))
    #     # result = {}
    #     # result['description'] = 'new project {0} deleted by {1}'.format(self.object.name, self.request.user.username)
    #     # result['url'] = noti.get_absolute_url()
    #     # ChannelGroup("notify-{}".format(self.object.organization.id)).send({"text": json.dumps(result)})
    #     # ChannelGroup("notify-0").send({"text": json.dumps(result)})
    #     return HttpResponseRedirect(self.get_success_url())
    # 
示例17
def ajax_upload_sites(request, pk):
    form = UploadFileForm(request.POST, request.FILES)
    if form.is_valid():
        count = 0
        project = Project(pk=pk)
        try:
            sites = request.FILES['file'].get_records()
            count = len(sites)
            with transaction.atomic():
                for site in sites:
                    site = dict((k,v) for k,v in site.iteritems() if v is not '')
                    lat = site.get("longitude", 85.3240)
                    long = site.get("latitude", 27.7172)
                    location = Point(lat, long, srid=4326)
                    type_id = int(site.get("type", "0"))
                    _site, created = Site.objects.get_or_create(identifier=str(site.get("id")), name=site.get("name"),
                                                                project=project, type_id=type_id)
                    _site.phone = site.get("phone")
                    _site.address = site.get("address")
                    _site.public_desc = site.get("public_desc"),
                    _site.additional_desc = site.get("additional_desc")
                    _site.location=location
                    if type_id:
                        _site.type = SiteType.objects.get(pk=type_id)
                    _site.save()
            if count:
                noti = project.logs.create(source=request.user, type=12, title="Bulk Sites",
                                       organization=project.organization,
                                       project=project, content_object=project,
                                       extra_message=count + "Sites",
                                       description='{0} created a {1} sites in {2}'.
                                           format(request.user.get_full_name(), count, project.name))
                result = {}
                result['description'] = noti.description
                result['url'] = noti.get_absolute_url()
                ChannelGroup("project-{}".format(project.id)).send({"text": json.dumps(result)})
            return Response({'msg': 'ok'}, status=status.HTTP_200_OK)
        except Exception as e:
            return Response({'file':e.message}, status=status.HTTP_400_BAD_REQUEST)
    return Response(form.errors, status=status.HTTP_400_BAD_REQUEST) 
示例18
def form_valid(self, form):
        self.object = form.save(project_id=self.kwargs.get('pk'), region_id=self.kwargs.get('region_pk'), new=True)
        noti = self.object.logs.create(source=self.request.user, type=11, title="new Site",
                                       organization=self.object.project.organization,
                                       project=self.object.project, content_object=self.object, extra_object=self.object.project,
                                       description='{0} created a new site named {1} in {2}'.format(self.request.user.get_full_name(),
                                                                                 self.object.name, self.object.project.name))
        result = {}
        result['description'] = '{0} created a new site named {1} in {2}'.format(self.request.user.get_full_name(),
                                                                                 self.object.name, self.object.project.name)
        result['url'] = noti.get_absolute_url()
        ChannelGroup("project-{}".format(self.object.project.id)).send({"text": json.dumps(result)})
        # ChannelGroup("notify-0").send({"text": json.dumps(result)})

        return HttpResponseRedirect(self.get_success_url()) 
示例19
def ws_paramiko_proxy_c(message):
    # print(dir(Group('paramiko')))
    Group('paramiko').add(message.reply_channel)
    message.reply_channel.send({'accept':True}) 
示例20
def ws_paramiko_proxy_d(message):
    Group('paramiko').discard(message.reply_channel) 
示例21
def ws_webshell(message,id):
    content = json.loads(message.content['text'])
    msg = dict(cmd='stream',data=content['cmd'],id=id,reply_channel=message.reply_channel.name)
    Group('paramiko').send({'text':json.dumps(msg)}) 
示例22
def ws_webshell_d(message,id):
    msg = dict(cmd='discard',reply_channel=message.reply_channel.name)
    Group('paramiko').send({'text':json.dumps(msg)}) 
示例23
def new_game_handler(**kwargs):
    """
    When a new game is created, this builds a list of all open games and 
    sends it down to all channels in the 'lobby' group
    """
    # if new
    if kwargs['created']:
        # send the latest list to all channels in the "lobby" group
        # the Group's send method requires a dict
        # we pass "text" as the key and then serialize the list of open games
        avail_game_list = Game.get_available_games()
        avail_serializer = GameSerializer(avail_game_list, many=True)
        Group('lobby').send({'text': json.dumps(avail_serializer.data)}) 
示例24
def perform_create(self, serializer):
        # from rest_framework.exceptions import ValidationError

        data = self.request.data

        # if "form" not in data:
        #     raise ValidationError({
        #         "form": "No Form Selected ",
        #     })
        # if data.has_key('site'):
        #     if FieldSightXF.objects.filter(xf=data["form"], is_scheduled=True, site=data["site"]).exists():
        #         raise ValidationError({
        #             "form": "Form Already Used ",
        #         })
        #     if FieldSightXF.objects.filter(xf=data["form"],is_scheduled=True, project=data["project"]).exists():
        #         raise ValidationError({
        #             "form": "Form Already Used ",
        #         })

        schedule = serializer.save()



        fxf = FieldSightXF(xf_id=data["xf"], is_scheduled=True, schedule=schedule, site=schedule.site,
                                    project=schedule.project, default_submission_status=data.get('default_submission_status', 0))
        if data.has_key("site"):
            fxf.is_deployed = True
            fxf.from_project = False
            fxf.save()
            noti = fxf.logs.create(source=self.request.user, type=19, title="Schedule",
                                  organization=fxf.site.project.organization,
                                  project = fxf.site.project,
                                  site = fxf.site, content_object=fxf, extra_object = fxf.site,
                                              extra_message='{0} form {1}'.format(fxf.form_type(), fxf.xf.title),
                                  description='{0} assigned new Schedule form  {1} to {2} '.format(
                                      self.request.user.get_full_name(),
                                      fxf.xf.title,
                                      fxf.site.name
                                  ))
            result = {}
            result['description'] = noti.description
            result['url'] = noti.get_absolute_url()
            ChannelGroup("site-{}".format(fxf.site.id)).send({"text": json.dumps(result)})
            ChannelGroup("project-{}".format(fxf.site.project.id)).send({"text": json.dumps(result)})
        else:
            fxf.save()
            noti = fxf.logs.create(source=self.request.user, type=18, title="Schedule",
                      organization=fxf.project.organization,
                      project = fxf.project, content_object=fxf, extra_object=fxf.project, extra_message='{0} form {1}'.format(fxf.form_type(), fxf.xf.title),
                      description='{0} assigned new Schedule form  {1} to {2} '.format(
                          self.request.user.get_full_name(),
                          fxf.xf.title,
                          fxf.project.name
                      ))
            result = {}
            result['description'] = noti.description
            result['url'] = noti.get_absolute_url()
            # ChannelGroup("site-{}".format(fxf.site.id)).send({"text": json.dumps(result)})
            ChannelGroup("project-{}".format(fxf.project.id)).send({"text": json.dumps(result)}) 
示例25
def set_deploy_stages(request, is_project, pk):
    try:
        if is_project == "1":
            project = Project.objects.get(pk=pk)
            sites = project.sites.filter(is_active=True)
            main_stages = project.stages.filter(stage__isnull=True)
            with transaction.atomic():

                FieldSightXF.objects.filter(is_staged=True, site__project=project, stage__isnull=False).\
                    update(stage=None, is_deployed=False, is_deleted=True)
                FieldSightXF.objects.filter(is_staged=True, project=project,is_deleted=False).update(is_deployed=True)
                Stage.objects.filter(site__project=project).delete()
                for main_stage in main_stages:
                    # sites = []
                    for site in sites:
                        # sites.append(site.id)
                        # send_message_stages(site)
                        site_main_stage = Stage(name=main_stage.name, order=main_stage.order, site=site,
                                           description=main_stage.description, project_stage_id=main_stage.id)
                        site_main_stage.save()
                        project_sub_stages = Stage.objects.filter(stage__id=main_stage.pk, stage_forms__is_deleted=False)
                        for project_sub_stage in project_sub_stages:
                            site_sub_stage = Stage(name=project_sub_stage.name, order=project_sub_stage.order, site=site,
                                           description=project_sub_stage.description, stage=site_main_stage, project_stage_id=project_sub_stage.id, weight=project_sub_stage.weight)
                            site_sub_stage.save()
                            if FieldSightXF.objects.filter(stage=project_sub_stage).exists():
                                fsxf = FieldSightXF.objects.filter(stage=project_sub_stage)[0]
                                site_fsxf, created = FieldSightXF.objects.get_or_create(is_staged=True, default_submission_status=fsxf.default_submission_status, xf=fsxf.xf, site=site,
                                                                   fsform=fsxf, stage=site_sub_stage)
                                site_fsxf.is_deleted = False
                                site_fsxf.is_deployed = True
                                site_fsxf.save()
            # noti = project.logs.create(source=request.user, type=4, title="Project Stages Deployed",
            # organization=project.organization, description="Project Stages Deployed to sites.")
            # result = {}
            # result['description'] = "Project Form Deployed to sites."
            # result['url'] = noti.get_absolute_url()
            # ChannelGroup("notify-{}".format(project.organization.id)).send({"text": json.dumps(result)})
            # ChannelGroup("notify-0").send({"text": json.dumps(result)})
            return HttpResponse({'msg': 'ok'}, status=status.HTTP_200_OK)
        else:
            site = Site.objects.get(pk=pk)
            site.site_forms.filter(is_staged=True, xf__isnull=False, is_deployed=False, is_deleted=False).update(is_deployed=True)
            send_message_stages(site)
            # noti = site.logs.create(source=request.user, type=4, title="Site Stages Deployed",
            # organization=site.project.organization, description="Project Form Deployed to sites.")
            # result = {}
            # result['description'] = "Project Form Deployed to sites."
            # result['url'] = noti.get_absolute_url()
            # ChannelGroup("notify-{}".format(site.project.organization.id)).send({"text": json.dumps(result)})
            # ChannelGroup("notify-0").send({"text": json.dumps(result)})
            return HttpResponse({'msg': 'ok'}, status=status.HTTP_200_OK)
    except Exception as e:
        return HttpResponse({'error':e.message}, status=status.HTTP_400_BAD_REQUEST) 
示例26
def post(self, request, pk, *args, **kwargs):
        data = json.loads(self.request.body)
        projects = data.get('projects')
        users = data.get('users')
        group = Group.objects.get(name=data.get('group'))
        group_id = Group.objects.get(name="Project Manager").id
        user = request.user
        org = get_object_or_404(Organization, pk=pk)
        task_obj = CeleryTaskProgress.objects.create(user=user, content_object = org, task_type=1)
        if task_obj:
            task = multiuserassignproject.delay(task_obj.pk, user, pk, projects, users, group_id)
            task_obj.task_id=task.id
            task_obj.save()
            return HttpResponse("Sucess")
        else:
            return HttpResponse("Failed")


#May need it
# class MultiUserAssignProjectView(OrganizationRoleMixin, TemplateView):
#     def get(self, request, pk):
#         org_obj = Organization.objects.get(pk=pk)
#         return render(request, 'fieldsight/multi_user_assign.html',{'type': "project", 'pk':pk})

#     def post(self, request, *args, **kwargs):
#         data = json.loads(self.request.body)
#         projects = data.get('projects')
#         users = data.get('users')
     

#         group = Group.objects.get(name="Project Manager")
#         for project_id in projects:
#             project = Project.objects.get(pk=project_id)
#             for user in users:
#                 role, created = UserRole.objects.get_or_create(user_id=user, project_id=project_id,
#                                                                organization__id=project.organization.id,
#                                                                project__id=project_id,
#                                                                group=group, ended_at=None)
#                 if created:
#                     description = "{0} was assigned  as Project Manager in {1}".format(
#                         role.user.get_full_name(), role.project)
#                     noti = role.logs.create(source=role.user, type=6, title=description, description=description,
#                      content_object=role.project, extra_object=self.request.user)
#                     result = {}
#                     result['description'] = description
#                     result['url'] = noti.get_absolute_url()
#                     ChannelGroup("notify-{}".format(role.organization.id)).send({"text": json.dumps(result)})
#                     ChannelGroup("project-{}".format(role.project.id)).send({"text": json.dumps(result)})
#                     ChannelGroup("notify-0").send({"text": json.dumps(result)})
#         return HttpResponse("Sucess") 
示例27
def whois(request):

    mimetype = 'application/json'

    # Get channel_layer function
    from channels.asgi import get_channel_layer
    from channels.sessions import session_for_reply_channel
            
    # passing group_channel takes channel name
    #channel_layer = get_channel_layer()
    #data = channel_layer.group_channels('notifications')
    #data = channel_layer.global_statistics()
    #data = channel_layer.channel_statistics('notifications')
    #data = get_channel_layer().group_channels('notifications')    
    #data = Group("notifications").extensions
    #data = get_channel_layer().receive_twisted()
    
    #from channels import channel_layers
    #layer = channel_layers["default"]
    #print(layer.router.channels)    
    
    data = []
    
    
    from django.contrib.sessions.backends import cache as engine
    data = get_channel_layer().group_channels('notifications')
    
    active_users = []
    for C in data:        
        #Channel(C).send({"text": json.dumps({'clean_signal':True})})
        c_session = session_for_reply_channel(C)        
        session = engine.SessionStore(c_session._session_key)        
        
        #print(c_session._session['_auth_user_id'])
        #print(session.keys())
        #print(session.get('username', None), session.get_expiry_date())
        
        username = session.get('username', None)
        # this is the same
        # username = c_session.get('username', None)
        if username not in active_users and username != None:
            active_users.append(username)
    data = active_users
            
    
    return HttpResponse(json.dumps(data), mimetype)