本文整理汇总了Python中ws4redis.publisher.RedisPublisher.publish_message方法的典型用法代码示例。如果您正苦于以下问题:Python RedisPublisher.publish_message方法的具体用法?Python RedisPublisher.publish_message怎么用?Python RedisPublisher.publish_message使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类ws4redis.publisher.RedisPublisher
的用法示例。
在下文中一共展示了RedisPublisher.publish_message方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: redisPublishMessage
# 需要导入模块: from ws4redis.publisher import RedisPublisher [as 别名]
# 或者: from ws4redis.publisher.RedisPublisher import publish_message [as 别名]
def redisPublishMessage(msj):
redis_publisher = RedisPublisher(facility='foobar', broadcast=True)
message = RedisMessage(msj)
redis_publisher.publish_message(message)
示例2: ws_call
# 需要导入模块: from ws4redis.publisher import RedisPublisher [as 别名]
# 或者: from ws4redis.publisher.RedisPublisher import publish_message [as 别名]
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')))
示例3: connectionCheck
# 需要导入模块: from ws4redis.publisher import RedisPublisher [as 别名]
# 或者: from ws4redis.publisher.RedisPublisher import publish_message [as 别名]
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")
示例4: interop_error_handler
# 需要导入模块: from ws4redis.publisher import RedisPublisher [as 别名]
# 或者: from ws4redis.publisher.RedisPublisher import publish_message [as 别名]
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)
示例5: handle
# 需要导入模块: from ws4redis.publisher import RedisPublisher [as 别名]
# 或者: from ws4redis.publisher.RedisPublisher import publish_message [as 别名]
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')
示例6: display
# 需要导入模块: from ws4redis.publisher import RedisPublisher [as 别名]
# 或者: from ws4redis.publisher.RedisPublisher import publish_message [as 别名]
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)
示例7: heartbeat
# 需要导入模块: from ws4redis.publisher import RedisPublisher [as 别名]
# 或者: from ws4redis.publisher.RedisPublisher import publish_message [as 别名]
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
示例8: library
# 需要导入模块: from ws4redis.publisher import RedisPublisher [as 别名]
# 或者: from ws4redis.publisher.RedisPublisher import publish_message [as 别名]
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)
示例9: postHeartbeat
# 需要导入模块: from ws4redis.publisher import RedisPublisher [as 别名]
# 或者: from ws4redis.publisher.RedisPublisher import publish_message [as 别名]
def postHeartbeat(self, request, pk=None):
global EXPIRATION
#check for seperate cache entry
"""
if (cache.get('heartbeat') != None): #trigger would be 'heartbeat' for status of heartbeats
#SEND TRIGGER IN THIS CASE TO START
"""
if not cache.has_key('heartbeat'):
#if doesn't have key heartbeat set its cache entry
cache.set('heartbeat','connected',EXPIRATION)
else:
#else delete the old one
cache.delete('heartbeat')
#create a new one
cache.set('heartbeat','connected',EXPIRATION)
#ONCE STARTS RECEIVING HEARTBEATS
#cache.set('heartbeat', 'triggering', EXPIRATION)
#ONCE STOPS RECEIVING HEARTBEATS
#cache.set('heartbeat','stopped', EXPIRATION)
if cache.get('trigger') == 1:
redis_publisher = RedisPublisher(facility="viewer",sessions=gcsSessions())
redis_publisher.publish_message(RedisMessage(json.dumps({'triggering':'true','time':cache.get("time")})))
elif cache.get('trigger')== 0:
redis_publisher = RedisPublisher(facility="viewer",sessions=gcsSessions())
redis_publisher.publish_message(RedisMessage(json.dumps({'triggering':'false'})))
if (cache.has_key('trigger')):
return Response({'heartbeat':cache.get('trigger')})
else:
return Response({})
示例10: targetCreate
# 需要导入模块: from ws4redis.publisher import RedisPublisher [as 别名]
# 或者: from ws4redis.publisher.RedisPublisher import publish_message [as 别名]
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")
示例11: select
# 需要导入模块: from ws4redis.publisher import RedisPublisher [as 别名]
# 或者: from ws4redis.publisher.RedisPublisher import publish_message [as 别名]
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.",
})
示例12: catch
# 需要导入模块: from ws4redis.publisher import RedisPublisher [as 别名]
# 或者: from ws4redis.publisher.RedisPublisher import publish_message [as 别名]
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)
示例13: get
# 需要导入模块: from ws4redis.publisher import RedisPublisher [as 别名]
# 或者: from ws4redis.publisher.RedisPublisher import publish_message [as 别名]
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)
示例14: new_group
# 需要导入模块: from ws4redis.publisher import RedisPublisher [as 别名]
# 或者: from ws4redis.publisher.RedisPublisher import publish_message [as 别名]
def new_group(request):
groupname = request.POST.get("groupname")
totwords = request.POST.get("totwords")
totmembers = request.POST.get('totmembers')
pref = settings.MY_PREFIX
prefg = pref+":"+groupname
user = str(request.user)
rd = StrictRedis()
# the above statements are self explanatory
exists = rd.exists(pref+":"+groupname)
if exists:
# return error, can't create the group with that name
# don't do that, just add this user to the already existing group
# if group size < totmembers
d = rd.hgetall(prefg+":hash")
response = {'facility':""}
if int(d['totmembers'])>int(d['curmembers']):
rd.hincrby(prefg+":hash", 'curmembers')
#d = rd.hgetall(prefg+":hash")
response['facility'] = groupname
response['new_group_created'] = False
rd.sadd(prefg, user)
#now notify the others that this user joined the group!
redis_publisher = RedisPublisher(facility = pref, broadcast = True)
mydict = {"type":"new_join", 'who':user, 'name':groupname}
msgstring = json.dumps(mydict)
print "broadcast message:"+msgstring
message = RedisMessage(msgstring)
redis_publisher.publish_message(message)
# now check if the competition is ready to start
if int(d['totmembers'])-1 == int(d['curmembers']):
start_competition(request,groupname)
return JsonResponse(response)
# so the group doesn't exist
rd.sadd(prefg, user)
# add this user to the set of all the users that are part of this group
hashdict = {'totwords':totwords, 'totmembers':totmembers, "owner":user, "name":groupname, 'curmembers':1}
# adding group name is redundant but it simplifies things a lot
rd.hmset(prefg+":hash", hashdict)
# using hash greatly simplifies the things(dict interconversion hgetall()), though i feel that the
# naming convention used is horrible
redis_publisher = RedisPublisher(facility = pref, broadcast = True)
mydict = {"type":"new_group"}
mydict.update(hashdict)
msgstring = json.dumps(mydict)
print msgstring
message = RedisMessage(msgstring)
redis_publisher.publish_message(message)
# notify the others about this new group that was created
rd.sadd(pref+":groups", groupname)
return JsonResponse({'facility':groupname, 'new_group_created':True})
示例15: MessageService
# 需要导入模块: from ws4redis.publisher import RedisPublisher [as 别名]
# 或者: from ws4redis.publisher.RedisPublisher import publish_message [as 别名]
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)