本文整理汇总了Python中redis.StrictRedis.publish方法的典型用法代码示例。如果您正苦于以下问题:Python StrictRedis.publish方法的具体用法?Python StrictRedis.publish怎么用?Python StrictRedis.publish使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类redis.StrictRedis
的用法示例。
在下文中一共展示了StrictRedis.publish方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: log
# 需要导入模块: from redis import StrictRedis [as 别名]
# 或者: from redis.StrictRedis import publish [as 别名]
def log(self, result, status):
provision_id = os.environ.get('PROVISION_ID')
data = {
'host': result._host.get_name(),
'provision_id': provision_id,
'log': result._result.get('msg'),
'status': status,
'task': result._task.get_name(),
'timestamp': datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S:%f'),
'type': 'log',
}
redis_host = os.environ.get('REDIS_HOST')
redis = StrictRedis(host=redis_host)
message = dumps(data)
redis.publish('ansible', message)
mongodb_settings_string = os.environ.get('MONGODB_SETTINGS')
if mongodb_settings_string is not None:
set_relative_path()
from onelove.models.provision import Provision, Log
mongodb_settings = loads(mongodb_settings_string)
connect(
host=mongodb_settings['host'],
db=mongodb_settings['db'],
)
provision = Provision.objects.get(id=provision_id)
log = Log(
host=data['host'],
log=data['log'],
status=data['status'],
task=data['task'],
timestamp=data['timestamp'],
)
provision.logs.append(log)
provision.save()
示例2: send_friend_request
# 需要导入模块: from redis import StrictRedis [as 别名]
# 或者: from redis.StrictRedis import publish [as 别名]
def send_friend_request(request, recipient_id):
if request.is_ajax():
recipient = get_object_or_404(User, id=recipient_id)
redis_obj = StrictRedis(db=9)
try:
redis_obj.publish('notifications:%s' % recipient.username, 1)
except Exception, err:
print err
fr_obj = None
try:
fr_obj = FriendRequest.objects.get(
sender=request.user, recipient=recipient)
except:
fr_obj = FriendRequest.objects.create(
sender=request.user, recipient=recipient)
# Also create an entry in redis for this user.
# PubSub only works if the user is online and subscribed to the live
# stream
try:
# This is creating error;;
# hmset() takes exactly 3 arguments (10 given)
redis_obj.hmset(
'user:notify:%s' % request.user.id,
'obj_name', fr_obj._meta.object_name,
'obj_id', fr_obj.id,
'time_of', int(time()),
'was_viewed', 'false')
except:
pass
示例3: push
# 需要导入模块: from redis import StrictRedis [as 别名]
# 或者: from redis.StrictRedis import publish [as 别名]
def push(payload, ttl, priority, redis_host='localhost', redis_port=6379):
"""
Push a package to the queue
"""
connection = StrictRedis(host=redis_host, port=redis_port)
package = create_package_with_ttl(
payload=payload, ttl=float(ttl), score=float(priority))
connection.zadd(DEFAULT_REDIS_KEY, package.score, package.raw_entry)
connection.publish(DEFAULT_REDIS_KEY, 'new_message')
示例4: EventPublisher
# 需要导入模块: from redis import StrictRedis [as 别名]
# 或者: from redis.StrictRedis import publish [as 别名]
class EventPublisher(EventHandler):
def __init__(self, host, port):
if StrictRedis:
self.conn = StrictRedis(host=host, port=port)
self.conn.pubsub()
else:
console("events", "Unable to load redis python module; event publishing disabled")
self.conn = None
def publish(self, handler, sprint, type, **extraArgs):
data = {"type": type, "user": handler.session["user"].username}
data.update(extraArgs)
channel = EventPublisher.formatChannelName(sprint.project.name)
try:
self.conn.publish(channel, toJS(data))
except Exception:
pass
@staticmethod
def formatChannelName(projectName):
return re.sub("\W+", "_", projectName.lower())
# EventHandler interface
def newSprint(self, handler, sprint):
self.publish(handler, sprint, "newSprint", name=sprint.name)
def sprintInfoUpdate(self, handler, sprint, changes):
import sys
if changes["end"]:
self.publish(handler, sprint, "sprintExtend", end=changes["end"].strftime("%A, %B %d"))
if changes["addMembers"]:
self.publish(handler, sprint, "addMembers", usernames=[user.username for user in changes["addMembers"]])
def sprintAvailUpdate(self, handler, sprint):
self.publish(handler, sprint, "sprintAvailUpdate")
def newTask(self, handler, task):
self.publish(
handler,
task.sprint,
"newTask",
name=task.name,
assigned=[user.username for user in task.assigned],
hours=task.hours,
)
def taskUpdate(self, handler, task, field, value):
if isinstance(value, list) and len(value) > 0 and isinstance(value[0], User):
value = [user.username for user in value]
self.publish(handler, task.sprint, "taskUpdate", id=task.id, name=task.name, field=field, value=value)
def newNote(self, handler, note):
self.publish(handler, note.task.sprint, "newNote", taskName=note.task.name)
示例5: write_story
# 需要导入模块: from redis import StrictRedis [as 别名]
# 或者: from redis.StrictRedis import publish [as 别名]
def write_story(request):
if request.user.is_authenticated():
user_obj = request.user
profile_obj = get_object_or_404(Profile, user=user_obj)
year_of_birth = profile_obj.dob.year
if request.method == 'POST':
form = WriteStoryForm(request.POST)
if form.is_valid():
story = form.cleaned_data['story']
story_list = story.split('\n')
# Replacing the newlines with break tag...
story = '<br>'.join(story_list)
heading = form.cleaned_data['heading']
uploaded_on = request.POST.get('datepicker', '')
moods = request.POST['moods']
is_public = request.POST.get('public', '')
is_public = int(is_public)
dp_obj = DailyPhoto.objects.filter(user=user_obj, uploaded_on=uploaded_on)
if dp_obj:
if is_public:
for i in dp_obj:
i.is_public = False
i.save()
new_photo_id = request.POST.get('new_photo_id', '')
DailyPhoto.objects.filter(id=new_photo_id).update(
heading=heading,
story=story,
no_of_views=0,
moods=moods,
is_public=True if is_public else False,
uploaded_on=uploaded_on
)
thread.start_new_thread(share_photos, (request, new_photo_id))
messages.info(request, 'Story uploaded successfully')
# Set redis keyword for realtime notifications.
redis_obj = StrictRedis(db=9)
redis_obj.publish("notifications:%s" % user_obj.username, 1)
# TODO Save the activity in db.
return HttpResponseRedirect('/%s/photo-calendar' % user_obj.username)
else:
form = WriteStoryForm()
return render(request, 'users/write_story.html', {
'write_story_form': form,
'year_of_birth': year_of_birth,
})
示例6: RedisPubSub
# 需要导入模块: from redis import StrictRedis [as 别名]
# 或者: from redis.StrictRedis import publish [as 别名]
class RedisPubSub(object):
def __init__(self, redis=None, **kwargs):
if redis is not None:
self._redis = redis
else:
self._redis = Redis(**kwargs)
self._pubsub = self._redis.pubsub(ignore_subscribe_messages=True)
self._thread = None
self._callbacks = {}
self._last_error = None
def start(self):
if not self._thread:
self._thread = self._pubsub.run_in_thread(sleep_time=0.001)
# TODO change in next version
# self._thread = self._pubsub.run_in_thread(sleep_time=0.001,
# daemon=True)
def stop(self):
if self._thread is not None:
self._thread.stop()
self._thread = None
def close(self):
self.stop()
self._pubsub.close()
def publish_event(self, key, **kwargs):
key = "{}".format(key)
ev = DataEvent(key=key, **kwargs)
self._redis.publish(key, ev.to_json())
def register_callback(self, key, callback):
key = "{}".format(key)
self._callbacks[key] = callback
self._pubsub.psubscribe(**{key: self._route_callback})
self.start()
def _route_callback(self, message):
logger.info("Incomming Event: {}".format(message))
pattern = message["pattern"].decode("utf-8")
if pattern in self._callbacks:
try:
event = DataEvent.from_json(message["data"].decode("utf-8"))
key = message["channel"].decode("utf-8")
self._callbacks[pattern](key=key, event=event)
except Exception as e:
# TODO Python 3 Exception chaining
t, value, traceback = sys.exc_info()
self._last_error = "{}\n{}\n{}".format(t, value, traceback)
logger.error(self._last_error)
# Do not raise
# raise InternalError, ("callback raised exception"), traceback
else:
raise InternalError("no callback found")
示例7: test_start_command_via_queue
# 需要导入模块: from redis import StrictRedis [as 别名]
# 或者: from redis.StrictRedis import publish [as 别名]
def test_start_command_via_queue(self):
"""
Call the stop via queue command
"""
ctrl_man = ControlManager.factory(list())
rqc = RedisQueueConfiguration(self.__config)
redis = StrictRedis(connection_pool=rqc.create_redis_connection_pool())
redis.rpush(rqc.queue, 'START')
redis.publish('{:s}_PUBSUB_CH'.format(rqc.queue), '1')
sleep(5)
self.assertTrue(ctrl_man.server.running)
示例8: test_stop_command_via_queue
# 需要导入模块: from redis import StrictRedis [as 别名]
# 或者: from redis.StrictRedis import publish [as 别名]
def test_stop_command_via_queue(self):
"""
Call the stop via queue command
"""
ControlManager.factory(list())
self.assertTrue(ControlManager().command_handler.should_run)
rqc = RedisQueueConfiguration(self.__config)
redis = StrictRedis(connection_pool=rqc.create_redis_connection_pool())
redis.rpush(rqc.queue, 'STOP')
redis.publish('{:s}_PUBSUB_CH'.format(rqc.queue), '1')
sleep(5)
self.util_check_stopped()
示例9: match_players
# 需要导入模块: from redis import StrictRedis [as 别名]
# 或者: from redis.StrictRedis import publish [as 别名]
def match_players():
queue = RedisQueue("all_players")
_redis = StrictRedis(**REDIS_QUEUE_KWARGS)
while True:
if queue.qsize() < 2:
time.sleep(0.5)
continue
left, right = queue.get(), queue.get()
game_id = str(uuid4())
_redis.publish(left, game_id)
_redis.publish(right, game_id)
示例10: serve_chat
# 需要导入模块: from redis import StrictRedis [as 别名]
# 或者: from redis.StrictRedis import publish [as 别名]
def serve_chat(websocket, room_name):
client_uuid = uuid.uuid4()
# subscribe the client to channel
spawn(channel_listener, websocket, room_name, client_uuid)
conn = RedisConnection()
try:
while True:
# message from client
message = websocket.receive()
if message is None:
return
conn.publish("%s.%s" % (room_name, client_uuid), message)
finally:
websocket.close()
示例11: remove
# 需要导入模块: from redis import StrictRedis [as 别名]
# 或者: from redis.StrictRedis import publish [as 别名]
def remove(payload, redis_host='localhost', redis_port=6379):
"""
Remove a package (or packages if the payload matches multiple) from the
queue
"""
connection = StrictRedis(host=redis_host, port=redis_port)
packages = _get_packages_in_queue(connection)
packages_to_remove = [
package for package in packages if package.payload == payload]
if packages_to_remove:
LOG.debug(
'Removing the following packages: {}'.format(packages_to_remove))
entries_to_remove = [
package.raw_entry for package in packages_to_remove]
connection.zrem(DEFAULT_REDIS_KEY, *entries_to_remove)
connection.publish(DEFAULT_REDIS_KEY, 'new_message')
示例12: do_comment
# 需要导入模块: from redis import StrictRedis [as 别名]
# 或者: from redis.StrictRedis import publish [as 别名]
def do_comment(request, dailyphoto_id):
dp_obj = get_object_or_404(DailyPhoto, id=dailyphoto_id)
comment = request.POST.get('do_comment', '')
comment = comment.strip()
# Save the comment in DB.
print "Comment Text: ", comment
list_of_users_in_comment = [resub(r'\[|\]', r'', name)
for name in findall(r'\[[a-z0-9]+\]', comment)]
for nuser in list_of_users_in_comment:
print nuser
if comment:
Comments.objects.create(user=request.user,
dailyphoto=get_object_or_404(DailyPhoto, id=dailyphoto_id),
comment=comment,
)
redis_obj = StrictRedis(db=9)
redis_obj.publish("notifications:%s" % request.user.username, 1)
return HttpResponseRedirect(
reverse('users.views.browse_daily_photo_single', args=(str(dp_obj.user.username), dp_obj.key)))
示例13: playbook
# 需要导入模块: from redis import StrictRedis [as 别名]
# 或者: from redis.StrictRedis import publish [as 别名]
def playbook(self, provision_id, *args):
playbook_args = list(args)
playbook_args.insert(0, 'ansible-playbook')
playbook_args.append('--ssh-common-args')
playbook_args.append(
'-o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null'
)
provision = Provision.objects.get(id=provision_id)
provision.status = 'RUNNING'
provision.save()
redis_host = current_app.config['REDIS_HOST']
os.environ['PROVISION_ID'] = str(provision_id)
os.environ['REDIS_HOST'] = current_app.config['REDIS_HOST']
mongodb_settings = dumps(current_app.config['MONGODB_SETTINGS'])
os.environ['MONGODB_SETTINGS'] = mongodb_settings
redis = StrictRedis(host=redis_host)
data = {
'provision_id': provision_id,
'status': provision.status,
'type': 'log',
'timestamp': datetime.utcnow().strftime(datetime_format),
}
redis.publish('ansible', dumps(data))
result = subprocess.run(playbook_args)
if result.returncode != 0:
provision.status = 'FAILURE'
provision.save()
data['status'] = provision.status
redis.publish('ansible', dumps(data))
return provision.status
provision.status = 'SUCCESS'
provision.save()
data['status'] = provision.status
redis.publish('ansible', dumps(data))
return provision.status
示例14: SMAData
# 需要导入模块: from redis import StrictRedis [as 别名]
# 或者: from redis.StrictRedis import publish [as 别名]
class SMAData(SwarmDataCallback):
def __init__(self, swarm, redis_host='localhost', redis_port=6379, pub_channel='swarm.data'):
self.redis = StrictRedis(redis_host, redis_port, unix_socket_path=REDIS_UNIX_SOCKET)
super(SMAData, self).__init__(swarm)
self.pub_channel = pub_channel
def __call__(self, data):
""" Callback for sending data to SMA's dataCatcher/corrSaver """
# Publish the raw data to redis
subs = self.redis.publish(self.pub_channel, data)
# Info log the set
self.logger.info("Data sent to %d subscribers", subs)
示例15: StrictRedis
# 需要导入模块: from redis import StrictRedis [as 别名]
# 或者: from redis.StrictRedis import publish [as 别名]
print "Obtaining lock..."
db.query(func.pg_advisory_lock(413, 1)).scalar()
print "Lock obtained."
redis = StrictRedis(connection_pool=redis_pool)
while True:
current_time = int(time.time())
# Make sure a message is sent every 25 seconds so the long poll requests
# don't time out.
# XXX INCREASE THIS TO SEVERAL MINUTES
for chat_id in redis.zrangebyscore("longpoll_timeout", 0, current_time):
redis.publish("channel:%s" % chat_id, '{"messages":[]}')
if redis.hlen("chat:%s:online" % chat_id) != 0:
redis.zadd("longpoll_timeout", time.time() + 25, chat_id)
else:
redis.zrem("longpoll_timeout", chat_id)
# And do the reaping.
for dead in redis.zrangebyscore("chats_alive", 0, current_time):
print current_time, "Reaping ", dead
chat_id, session_id = dead.split("/")
user_id = redis.hget("chat:%s:online" % chat_id, session_id)
disconnected = disconnect(redis, chat_id, session_id)
# Only send a timeout message if they were already online.
if not disconnected:
print "Not sending timeout message."
continue