当前位置: 首页>>代码示例>>Python>>正文


Python publisher.RedisPublisher类代码示例

本文整理汇总了Python中ws4redis.publisher.RedisPublisher的典型用法代码示例。如果您正苦于以下问题:Python RedisPublisher类的具体用法?Python RedisPublisher怎么用?Python RedisPublisher使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了RedisPublisher类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: interop_error_handler

def interop_error_handler(error):
	code,reason,text = error.errorData()

	#response to client accordingly
	#but keep going...if something fails, respond and ignore it
	#alert mission planner about the error though
	if code == 400:
		return Response({'time':time()-startTime,'error':"WARNING: Invalid telemetry data. Skipping"})

	elif code == 404:
		return Response({'time':time()-startTime,'error':"WARNING: Server might be down"})

	elif code == 405 or code == 500:
		return Response({'time':time()-startTime,'error':"WARNING: Interop Internal Server Error"})
	#EXCEPT FOR THIS
	elif code == 403:
			creds = cache.get("Creds")
			times = 5
			for i in xrange(0,times):
				try:
					interop_login(username=creds['username'],password=creds['password'],server=creds['server'],tout=5)
					return Response({'time':time()-startTime,'error':"Had to relogin in. Succeeded"})
				except Exception as e:
					sleep(2)
					continue
			code,_,__ = e.errorData()
			#Everyone should be alerted of this
			resp = {'time':time()-startTime,'error':"CRITICAL: Re-login has Failed. We will login again when allowed\nLast Error was %d" % code}
			redis_publisher = RedisPublisher(facility='viewer',sessions=gcsSessions())
			redis_publisher.publish_message(RedisMessage(json.dumps({'warning':resp})))
			return Response(resp)
开发者ID:RUAutonomous,项目名称:DataProcessing,代码行数:31,代码来源:views.py

示例2: display

def display(msg, task_id, color=None, stderr=False, screen_only=False, log_only=False, runner=None):
    # prevent a very rare case of interlaced multiprocess I/O
    log_flock(runner)
    while msg.startswith("\n"):
        msg = msg.replace("\n", "")
    msg2 = msg + '\n'
    if color:
        msg2 = stringc(msg, color) + '\n'

    logger.debug('TASK_ID: {task_id} | MSG: {message}'.format(task_id=task_id, message=msg2))

    # Pusblish the message on websocket
    redis_publisher = RedisPublisher(facility=task_id, broadcast=True)
    redis_message = RedisMessage(msg2)
    redis_publisher.publish_message(message=redis_message)

    # Store the message into a redis list to let the user get all
    # history of the logs
    redis_connection.rpush('tasks:' + task_id, msg2)
    # reset the expire of the list
    if settings.WS4REDIS_EXPIRE:
        if settings.WS4REDIS_EXPIRE > 0:
            redis_connection.expire('tasks:' + task_id,
                                    settings.WS4REDIS_EXPIRE)
    log_unflock(runner)
开发者ID:discapacidad5,项目名称:cyclosible,代码行数:25,代码来源:callbacks_ansiblev1.py

示例3: heartbeat

 def heartbeat(self,websocketmsg):
     try:
         zom = Zombie.objects.get(host=websocketmsg.ip)
         redis_publisher = RedisPublisher(facility='attacker',sessions=[atkr.sesskey for atkr in Attacker.objects.all()])
         redis_publisher.publish_message(RedisMessage(simplejson.dumps({'new':'new','newzombieId':zom.pk,'newzombieHost':zom.host})))
     except Exception:
         pass
开发者ID:oneTimePad,项目名称:JSZombie,代码行数:7,代码来源:zombie.py

示例4: library

def library(request):
  if request.method == 'POST':
    library = json.loads(request.body.decode(encoding='utf-8'))
    print library
    for artist_title, artist_attrs in library.items():
        print('Adding artist:', artist_title)
        artist, created = Artist.objects.get_or_create(title=artist_title)
        for album_title, album_attrs in artist_attrs.items():
          print('Adding album:', album_title)
          album, created = Album.objects.get_or_create(title=album_title,
              artist=artist)
          for track_title, track_attrs in album_attrs.items():
            print('Adding track:', track_title)
            track, created = Track.objects.get_or_create(
                title=track_title, artist=artist, album=album,
                defaults={'session': request.session.session_key})
        print()

    publisher = RedisPublisher(facility='main', broadcast=True)
    message = json.dumps({'notification': 'library_updated'})
    publisher.publish_message(RedisMessage(message))
    return HttpResponse('OK')
  else:
    artists = Artist.objects.all()
    context = {'artists': artists}
    context.update(csrf(request))
    return render(request, 'playlistq/library.html', context)
开发者ID:0x414f,项目名称:playlistq3,代码行数:27,代码来源:views.py

示例5: ws_call

def ws_call(signal_name, request, sharing, kwargs):
    """ Call a JS signal from the Python side.

    :param signal_name: name of signal
    :type signal_name:
    :param request: a SignalRequest with session_key and username
    :type request: :class:`djangofloor.decorators.SignalRequest`
    :param sharing: the required sharing. Can be SESSION, USER or BROADCAST or any dict which is valid for django-websockets-redis.
    :type sharing:
    :param kwargs: options to pass to the JS signal
    :type kwargs:
    :return: `None`
    """
    if isinstance(sharing, binary_type):
        sharing = force_text(sharing)
    if sharing == SESSION:
        sharing = {SESSION: [request.session_key, ]}
    elif sharing == USER:
        sharing = {USER: [request.username, ]}
    elif sharing == BROADCAST:
        sharing = {BROADCAST: True}
    if BROADCAST in sharing:
        sharing[BROADCAST] = True
    redis_publisher = RedisPublisher(facility=settings.FLOOR_WS_FACILITY, **sharing)
    msg = json.dumps({'signal': signal_name, 'options': kwargs}, cls=get_signal_encoder())
    redis_publisher.publish_message(RedisMessage(msg.encode('utf-8')))
开发者ID:pombredanne,项目名称:django-floor,代码行数:26,代码来源:df_ws4redis.py

示例6: targetCreate

	def targetCreate(self,request,pk=None):
		#pdb.set_trace()
		connectionCheck()
		if not "scaleWidth" in request.data or int(request.data['scaleWidth'])==0 :
			return HttpResponseForbidden("No crop given!")
		if not "width" in request.data or int(request.data['width']) == 0:
			return HttpResponseForbidden("No crop given!")
		if not "height" in request.data or int(request.data['height']) ==0:
			return HttpResponseForbidden("No crop given!")
		try:
			picture = Picture.objects.get(pk=request.data['pk'])
		except Picture.DoesNotExist:
			return HttpResponseForbidden()
		target = TargetSerializer(data={key : (request.data[key] if key in request.data else None)  for key in ('background_color','alphanumeric_color','orientation','shape','alphanumeric','ptype','description')})
		if not target.is_valid():
			return HttpResponseForbidden()
		sizeData = request.data
		target = target.deserialize()
		if target.background_color == "grey":
			target.background_color = "gray"
		if target.alphanumeric_color =="grey":
			target.alphanumeric_color = "gray"
		target.crop(size_data=sizeData,parent_pic=picture)
		target.save()

		redis_publisher = RedisPublisher(facility='viewer',sessions=gcsSessions())
		redis_publisher.publish_message(RedisMessage(json.dumps({'target':'create','pk':target.pk,'image':TARGET+"/Target"+str(target.pk).zfill(4)+'.jpeg'})))
		return Response("success")
开发者ID:RUAutonomous,项目名称:DataProcessing,代码行数:28,代码来源:views.py

示例7: connectionCheck

def connectionCheck():

	if cache.has_key("checkallowed"):
		if not cache.has_key("android"):
			redis_publisher = RedisPublisher(facility='viewer',sessions=gcsSessions())
			redis_publisher.publish_message(RedisMessage(json.dumps({'disconnected':'disconnected'})))
			cache.delete("checkallowed")
开发者ID:RUAutonomous,项目名称:DataProcessing,代码行数:7,代码来源:views.py

示例8: catch

    def catch(self, request, format='xml'):
        '''
        Deals with the incoming payload,
        Creates a new message object connected to the Contact
        '''
        message = str(request.data['Body'])
        to_number = request.data['From']

        contact = Contact.objects.filter(phone_number=to_number).first()

        if not contact:
            print "Unknown contact messaging you"
            contact = Contact.objects.create(
                first_name='Unknown',
                last_name='',
                phone_number=to_number
                )

        new_message = Message.objects.create(
            text=message,
            contact=contact,
            )

        message_serialized = serialize(MessageSerializer(new_message))

        redis_publisher = RedisPublisher(facility='akalite', broadcast=True)
        web_message = RedisMessage(message_serialized)
        redis_publisher.publish_message(web_message)
      
        print('Message successfuly caught.')

        resp = twilio.twiml.Response()
        resp.message("Caught")

        return Response(None)
开发者ID:AdrianMalaran,项目名称:mygithubpage,代码行数:35,代码来源:viewsets.py

示例9: select

def select(request):
  track_ids = request.POST.getlist('track_ids')
  if track_ids:
    new_track = False
    for id in track_ids:
      selected = Track.objects.get(id=id)
      print 'selected:', selected
      try:
        position = PlaylistItem.objects.latest().position + 1
      except PlaylistItem.DoesNotExist:
        position = 0
        new_track = True
      print 'position:', position
      PlaylistItem(track=selected, position=position).save()
    else:
      print 'playlist:', [str(i.track) for i in PlaylistItem.objects.all()]
      publisher = RedisPublisher(facility='main', broadcast=True)
      message = json.dumps({'notification': 'playlist_updated'})
      publisher.publish_message(RedisMessage(message))
      if new_track:
        track = get_current_track()
        if track:
          if not track.file:
            request_track_file(track, request)
          else:
            notify_track_available(track)

    return HttpResponseRedirect(reverse('playlist'))
  return render(request, 'playlistq/album.html', {
    'error_message': "You didn't select a track.",
  })
开发者ID:0x414f,项目名称:playlistq3,代码行数:31,代码来源:views.py

示例10: get

    def get(self, request, *args, **kwargs):
        game_name = self.kwargs.get('game_name')
        context = RequestContext(request)
        moves = cache.get("game."+game_name)
        variables = {'moves': moves}
        game = (TicTacGameSession.objects.filter(name=game_name) or [None])[0]

        if game is None or (game.user != request.user and game.user2 is not None and game.user2 != request.user) or game.state == "over":
            return HttpResponseRedirect('/room_list/')
        if game.user != request.user and game.user2 is None:
            game.user2 = request.user
            game.state = "playing"
            game.save()

            redis_publisher = RedisPublisher(facility='foobar', users=[game.user])
            message = RedisMessage("start")
            redis_publisher.publish_message(message)
            redis_publisher.publish_message(RedisMessage(""))

            variables['my_turn'] = False
            variables['joined'] = True
            # kela
        elif game.user2 is None:
            variables['my_turn'] = True
            variables['joined'] = False
        else:
            variables['my_turn'] = False
            variables['joined'] = True
        variables['first_player'] = game.user == request.user
        variables['game_name'] = game_name
        # variables['second_player']
        print variables
        return render_to_response('tictac.html', variables, context_instance=context)
开发者ID:nitinatwork,项目名称:tic_tac_toe,代码行数:33,代码来源:views.py

示例11: redisPublishMessage

def redisPublishMessage(msj):

    redis_publisher = RedisPublisher(facility='foobar', broadcast=True)

    message = RedisMessage(msj)

    redis_publisher.publish_message(message)
开发者ID:vpino,项目名称:kit-de-servicios,代码行数:7,代码来源:redis.py

示例12: handle

 def handle(self, *args, **options):
     welcome = RedisMessage('Hello everybody')
     print "begin update unit pos"
     redis_publisher=RedisPublisher(facility='units_updated', users=[x for x in User.objects.all()])
     
     while True:
         sleep(1)
         start=clock()
         #self.stdout.write( "ruslix " )
         try:
             cursor = connection.cursor()
             cursor.execute('begin')
             cursor.execute('LOCK TABLE game_unit')
             #cursor.fetchone()
             d=datetime.now()
             t=unit.objects.filter(in_move__lte=d)
             for i in t:
                 i.in_move=None
                 i.save()
                 found_combat(i)
                 """for ii in neighbor:
                     print ii.user.user," lalala3  ",i.user.user
                 """
                 redis_publisher=RedisPublisher(facility='units_updated', users=[i.user.user,])
                 welcome = RedisMessage("unit moved "+str(i.pk))
                 redis_publisher.publish_message(welcome)
                 print i.pk,i.in_move,i.user
         finally:
             cursor.execute('commit')
开发者ID:despair1,项目名称:django_test,代码行数:29,代码来源:check_move.py

示例13: MessageService

class MessageService(object):
    """Service to handle messages, including local
    logging and publishing using Redis.
    """

    def __init__(self):
        self._redis_publisher = RedisPublisher(
            facility=settings.REDIS_PUBLISHER_FACILITY_LABEL,
            broadcast=True)
        self._log_lines = []

    def publish_message(self, line, **kwargs):
        """Publishes a messages using Redis. This line is sent to
        the web.

        The line could be an empty string
        """
        # Line could be an empty string: in case we need to inform
        # some situation to the web tier, we send a dict with flags,
        # but we don't want to send a log line.
        if line:
            self._log_lines.append(line)

        message_dict = {'line': line}
        message_dict.update(kwargs)

        self._redis_publisher.publish_message(
            RedisMessage(json.dumps(message_dict)))

    def log_and_publish(self, message, *args, **kwargs):
        """Log a line using and publish it to the web tier.

        The *args are passed to logger.info()
        The **kwargs are passed to '_send_line()'
        """
        logger.info(message, *args)
        record = LogRecord('name', logging.INFO, "(unknown file)", 0,
                           message, args, exc_info=None, func=None)
        full_message = record.getMessage()
        self.publish_message(line=full_message, **kwargs)
        # self._log_lines.append(message)

    def log_and_publish_error(self, message, *args, **kwargs):
        """Log a line using and send it to the web tier.
        The *args are passed to logger.info()
        The **kwargs are passed to '_send_line()'
        """
        logger.error(message, *args)
        record = LogRecord('name', logging.ERROR, "(unknown file)", 0,
                           message, args, exc_info=None, func=None)
        full_message = record.getMessage()
        updated_kwargs = dict(kwargs)
        updated_kwargs['errorLine'] = True
        self.publish_message(line=full_message, **updated_kwargs)
        # self._log_lines.append(message)

    def get_log(self):
        """Returns the saved log lines as a single string"""
        return "\n".join(self._log_lines)
开发者ID:data-tsunami,项目名称:smoke,代码行数:59,代码来源:messages.py

示例14: send_capture

def send_capture(player1, player2, pos):
    redis_publisher = RedisPublisher(facility='game_move',
             users=[player1.user.username, player2.user.username])
    message = {}
    message['capture'] = True
    message['pos'] = pos
    message = RedisMessage(json.dumps(message))
    redis_publisher.publish_message(message)
开发者ID:dlareau,项目名称:Tafl_webapp,代码行数:8,代码来源:redis.py

示例15: post

 def post(self, request, *args, **kwargs):
     print request.POST
     redis_publisher = RedisPublisher(facility='foobar', users=[request.POST.get('user')])
     print redis_publisher
     message = RedisMessage(request.POST.get('message'))
     print message
     redis_publisher.publish_message(message)
     return HttpResponse('OK')
开发者ID:ximepa,项目名称:xbills,代码行数:8,代码来源:views.py


注:本文中的ws4redis.publisher.RedisPublisher类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。