def sse_push_message(request):
    #if request.method == 'POST':
    r = redis_connection()
        #dd = Usernote.objects.create(title=request.POST['message'])
    #d = UsernoteSerializer(dd)
    send_event("myevent",json.dumps('hai'))
    return HttpResponse('OK')
Beispiel #2
0
def pushToClient(request):
    """
    主动推送信息到前端
    """
    logger.warning('123414')
    send_event('myevent', 'xxxxxxx', channel = 'foo')
    return HttpResponse('zzzzz')
Beispiel #3
0
def publish(uuid, **kwargs):
    data = {
        'uuid': uuid,
        'extra': kwargs.pop('extra', None),
        'type': kwargs.pop('type', None)
    }
    data.update(kwargs)
    send_event(event_name='login', data=json.dumps(data), channel='wechat')
Beispiel #4
0
def pushToClient(event_name, user_name, result):
    """
    主动推送信息到前端
    """
    logger.info('name is {}, result is {}, username is {}'.format(event_name, result, user_name))
    send_event(event_name, json.dumps({
        'result': result
    }), channel = SSE_CHANNEL_TEMPLATE.format(user_name))
 def send_event(self, event):
     data = {}
     data.update({'item': utils.get_serializer_class(
         self.__class__.__name__)(instance=self).data})
     data.update(
         {'model_name': utils.get_model_name(self.__class__.__name__)})
     send_event(event, UnicodeJSONRenderer()
                .render(data=data), channel="stream")
Beispiel #6
0
def alarm_notify(sender=None, **kwargs):
    inform_teams = kwargs["inform_teams"]
    channels = [team.id for team in inform_teams]
    message = json.dumps({
        'type': 'foo',
        'html': "news",
    })
    for channel in channels:
        send_event('message', message, channel) # named channel
    return True
Beispiel #7
0
def process(tweet):
    """
    Responsible for picking out
    hashtags from JSON and updating
    redis
    """
    for tag in tweet["entities"]["hashtags"]:
        hashtag = tag["text"].encode("utf8").lower()
        result = redis.zincrby("hashtags", hashtag, 1)
        # logger.info('Incremented #%s: %s' % (hashtag, result))
        send_event("increment", json.dumps([hashtag, int(result)]))
Beispiel #8
0
def new_msg_notify(receiver_id, clean=False):
    """
    Publish new message notification to redis for the user, then FE listener could get new message count

    :param receiver_id: user PUID retrieved from wxpy.bot
    :param clean: indicate whether to delete the corresponding key in redis
    """
    if clean:
        clean_msg_notify(receiver_id)
    event_name = 'notification'
    data = {'count': Notification.count_by_receiver_id(receiver_id)}
    send_event(event_name=event_name, data=json.dumps(data), channel='wechat')
Beispiel #9
0
def remove(request, game_id, player_id):
    """
    Update game of a player that lost.
    """
    
    curr_game = get_object_or_404(Game, pk=game_id)
    curr_player = get_object_or_404(Player, pk=player_id)
    curr_game.remove_player(curr_player)
    curr_game.save()
    
    # Sending event
    players_left = curr_game.get_players()
    player_pks = [player.pk for player in players_left]
    json_data = json.dumps({'players': player_pks})
    send_event("player_update", json_data, channel='game{}'.format(game_id))
    
    return HttpResponse()
Beispiel #10
0
def chat_view(request, pk):
    chat = Chat.objects.get(pk=pk)
    if request.user.profile in chat.users.all() or pk == '1':
        error_code = 0
        error_text = ''
        channel = 'channel_' + str(pk)
        SSE.redis_channel = channel
        if request.is_ajax() and request.method == 'GET' and request.GET.get("text").strip() != '':
                data = {
                    'u_pk': int(request.user.profile.pk),
                    'time': time.strftime("%H:%M:%S", time.localtime()),
                    'user': request.user.profile.get_fullname(),
                    'text': request.GET.get("text"),
                    'read': [int(request.user.profile.pk), ]
                }
                send_event("send_message", json.dumps(data), channel=SSE.redis_channel)
                r = redis.Redis('127.0.0.1')
                r.rpush(SSE.redis_channel, data)
                return HttpResponse(json.dumps({'error_code': error_code, 'error_text': error_text}), content_type="application/json")
        return render(request, 'accounts/chat.html', {'channel': channel, 'pk': pk, 'chat': chat})
    else:
        return redirect('/account/')
Beispiel #11
0
def clock(request, game_id):
    """
    Start the clock on a given game.
    """
    
    curr_game = get_object_or_404(Game, pk=game_id)
    is_running_str = request.GET.get('is_running', '')
    is_running = json.loads(is_running_str)
    if is_running:
        curr_game.start_playing()
    else:
        curr_game.pause_playing()
        
    curr_game.save()
    
    # Sending event
    level, time_left = curr_game.get_blind_state()
    json_data = json.dumps({'is_running': is_running, 'level': level, 
                            'time': time_left})
    send_event("clock_update", json_data, channel='game{}'.format(game_id))
    
    return HttpResponse()
Beispiel #12
0
def sse(level, pk, message, extra_tags, subject, user, from_user):
    """
    :type user: basestring
    :type from_user: basestring
    """

    msg = json.dumps(dict(
        level=constants.DEFAULT_TAGS.get(level), pk=pk,
        message=message,
        extra_tags=extra_tags,
        subject=subject, from_user=from_user))

    if settings.TESTING:
        #
        # Please see notes in monitio.conf.settings and monitio.notify.sse
        #
        warnings.warn(
            "Testing mode - I will fake sending SSE messages and bypass Redis")
        testutil.MESSAGES.append(msg)
        return

    send_event("message", msg, channel=user)
Beispiel #13
0
def login(request):
    user = get_logged_in_user(current_bot)
    logger.info(current_bot.registered)
    logger.info(current_bot.listening_thread)
    logger.info(user)
    try:
        from wechat.tasks import retrieve_data
        rs = retrieve_data.delay(update=True)
        logger.info("任务id为: {}".format(rs.id))
    except Exception as e:
        logger.error(e)

    if user:
        serializer = UserSerializer(instance=user)
        data = {'type': 'logged_in', 'user': copy.deepcopy(serializer.data)}
        send_event(event_name='login', data=json.dumps(data), channel='wechat')
        # task_id = r.get(LISTENER_TASK_KEY)
        # if task_id:
        # task_id = app.send_task('wechat.tasks.bot_msg_listener')
        # r.set(LISTENER_TASK_KEY, task_id)
        return Response(serializer.data, status=status.HTTP_201_CREATED)
    else:
        return Response(status=status.HTTP_400_BAD_REQUEST)
Beispiel #14
0
 def post(self, request):
     send_event('message', u"sent at %s — %s" % (now(), request.POST.get('message', '')))
     return HttpResponse(json.dumps({'status': 'ok'}))
Beispiel #15
0
def collect_status(state):
    redis.set("collect_status", state)
    send_event("celery_status", state)
Beispiel #16
0
def sse_incr(request):
    r = redis_connection()
    count = r.incr('sheeple')
    send_event("myevent", json.dumps(count))
    return HttpResponse('OK')
Beispiel #17
0
def sse_delete(request):
    r = redis_connection()
    r.delete('sheeple')
    send_event("myevent", json.dumps(0))
    return HttpResponse()