本文整理汇总了Python中redis.get函数的典型用法代码示例。如果您正苦于以下问题:Python get函数的具体用法?Python get怎么用?Python get使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了get函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: resubmit_jobs
def resubmit_jobs():
if config.get('ckan.harvest.mq.type') != 'redis':
return
redis = get_connection()
log.debug('_create_or_update_package')
harvest_object_pending = redis.keys('harvest_object_id:*')
for key in harvest_object_pending:
date_of_key = datetime.datetime.strptime(redis.get(key),
"%Y-%m-%d %H:%M:%S.%f")
if (datetime.datetime.now() - date_of_key).seconds > 180: # 3 minuites for fetch and import max
redis.rpush('harvest_object_id',
json.dumps({'harvest_object_id': key.split(':')[-1]})
)
redis.delete(key)
harvest_jobs_pending = redis.keys('harvest_job_id:*')
for key in harvest_jobs_pending:
date_of_key = datetime.datetime.strptime(redis.get(key),
"%Y-%m-%d %H:%M:%S.%f")
if (datetime.datetime.now() - date_of_key).seconds > 7200: # 3 hours for a gather
redis.rpush('harvest_job_id',
json.dumps({'harvest_job_id': key.split(':')[-1]})
)
redis.delete(key)
示例2: resubmit_jobs
def resubmit_jobs():
'''
Examines the fetch and gather queues for items that are suspiciously old.
These are removed from the queues and placed back on them afresh, to ensure
the fetch & gather consumers are triggered to process it.
'''
if config.get('ckan.harvest.mq.type') != 'redis':
return
redis = get_connection()
# fetch queue
harvest_object_pending = redis.keys(get_fetch_routing_key() + ':*')
for key in harvest_object_pending:
date_of_key = datetime.datetime.strptime(redis.get(key),
"%Y-%m-%d %H:%M:%S.%f")
# 3 minutes for fetch and import max
if (datetime.datetime.now() - date_of_key).seconds > 180:
redis.rpush(get_fetch_routing_key(),
json.dumps({'harvest_object_id': key.split(':')[-1]})
)
redis.delete(key)
# gather queue
harvest_jobs_pending = redis.keys(get_gather_routing_key() + ':*')
for key in harvest_jobs_pending:
date_of_key = datetime.datetime.strptime(redis.get(key),
"%Y-%m-%d %H:%M:%S.%f")
# 3 hours for a gather
if (datetime.datetime.now() - date_of_key).seconds > 7200:
redis.rpush(get_gather_routing_key(),
json.dumps({'harvest_job_id': key.split(':')[-1]})
)
redis.delete(key)
示例3: hongbao
def hongbao():
"""
定期统计用户发送口令, 获取红包的情况
规则: 用户向派派发送口令, 获得红包
:return:
"""
from datetime import datetime
from bson import ObjectId
import re
redis = _redis_client()
# 获得已发红包的用户
processed_users = set(json.loads(redis.get('viae/viae.provisional.hongbao/processed_users') or '[]'))
# 获得红包处理进度的时间戳
utc_tz = timezone('UTC')
processed_since = redis.get('viae/viae.provisional.hongbao/processed_ts')
logger.info('Processing from %s' % processed_since)
processed_since = datetime.strptime(processed_since, '%Y-%m-%d %H:%M:%S').replace(tzinfo=utc_tz)
dummy_id = ObjectId.from_datetime(processed_since)
# 找到哪些用户发送过红包口令
pattern = re.compile(u'(体验旅行派APP领现金红包|新用户口令|领新用户红包|从微信过来领红包|下单送北京大房免费住)', re.IGNORECASE)
sender_list = mongo_hedy.Message.distinct('senderId',
{'_id': {'$gt': dummy_id}, 'receiverId': 10000, 'contents': pattern})
# 这些用户必须不在已发送红包的列表中, 并且为两天内注册的
final_senders = {}
user_dummy_id = ObjectId.from_datetime(processed_since - timedelta(days=7))
for s in filter(lambda v: v not in processed_users, sender_list):
u = mongo_yunkai.UserInfo.find_one({'userId': s, '_id': {'$gt': user_dummy_id}}, {'userId': 1, 'nickName': 1})
if not u:
continue
final_senders[u['userId']] = u
if final_senders:
# 准备报表
sections = []
for uid, user in sorted(final_senders.items(), key=lambda v: v[0]):
messages = mongo_hedy.Message.find({'senderId': uid, 'receiverId': 10000}, {'contents': 1})
c = '\n'.join([tmp['contents'] for tmp in messages])
sections.append(u'%d: %s\n%s\n\n' % (uid, user['nickName'], c))
processed_users.add(uid)
email_contents = ''.join(sections).strip()
from viae.job import send_email_to_group, send_email
logger.info('Sending hongbao stats')
send_email_to_group(groups='MARKETPLACE', subject=u'红包申请统计', body=email_contents)
# 默认7天过期
expire = 7 * 24 * 3600
redis.set('viae/viae.provisional.hongbao/processed_users', json.dumps(list(processed_users)), expire)
redis.set('viae/viae.provisional.hongbao/processed_ts',
(datetime.utcnow() - timedelta(minutes=20)).replace(tzinfo=utc_tz).strftime('%Y-%m-%d %H:%M:%S'), expire)
示例4: kill
def kill():
redis.incr('kills')
if request.forms.get("name"):
user = request.forms.get("name")
# print user
redis.incr(user)
return template('<b>Flies killed: {{num_killed}}</b>!', num_killed=redis.get(user))
else:
return template('<b>Flies killed: {{num_killed}}</b>!', num_killed=redis.get('kills'))
示例5: shorten_details
def shorten_details(short_id):
link_target = redis.get('url-target:' + short_id)
if link_target is None:
raise NotFound()
click_count = int(redis.get('click-count:' + short_id) or 0)
return render_template('details.html',
short_id=short_id,
click_count=click_count,
link_target=link_target)
示例6: _handle_message
def _handle_message(self, msg):
"""
Forwards messages from Redis to the players directly connected to this
instance.
"""
self._debug('RECEIVED - {}', extra=[str(msg)])
if msg['type'] != 'message' or msg['channel'] != self.topic:
return # Ignore messages we don't need
msg = json_loads(msg['data'])
# If we have the artist, we're responsible for adjusting game state
must_pass = False
artist = self._get_artist()
score = None
guesser = None
if self._has_artist(artist):
if msg.verb == 'GUESSED':
if msg.player_name == artist:
self._error('artist ({}) submitted a guess', extra=[artist])
else:
word = redis.get(self.word_key)
# TODO: Correct is only set for clients connected to this instance.
msg.correct = word.lower() == msg.word.lower()
if msg.correct:
guesser = msg.player_name
score = redis.zincrby(self.players_key, msg.player_name, 1)
word_won(word)
must_pass = True
elif msg.verb == 'SKIPPED':
if msg.player_name == artist:
self._error('artist ({}) voted to skip', extra=[artist])
else:
voted = redis.scard(self.skip_key)
total = redis.zcard(self.players_key) - 1
if voted * 2 > total:
must_pass = True
elif msg.verb == 'ENDED':
if msg.player_name == artist:
must_pass = True
# TODO: Player name will be sent on other instances
del msg.player_name
# Repeat the message to all players
for p in self.players:
if msg.verb == 'PASSED' and msg.player_name == p.name:
# Add the word to the passed message for the correct player
special = Message(msg)
special.word = redis.get(self.word_key)
gevent.spawn(p.send, special)
else:
gevent.spawn(p.send, msg)
if must_pass:
self._pass_turn(artist, guesser=guesser, score=score)
示例7: index
def index():
visitors = redis.get('visitors')
os = redis.get('osdata')
num = 0 if visitors is None else int(visitors)
num += 1
redis.set('visitors', num)
user_agent = request.user_agent
return render_template('index.html', number=num, user_agent=user_agent)
示例8: join
def join(self, player):
if player.table == self:
return # Already part of this table.
if player.table is not None:
player.table.leave(player) # Player has to leave old table
msg = Message('JOINED') # Tell all the other players
msg.player_name = player.name # that a new player has joined.
self.send(msg)
player.table = self # Register the new player with
self.players.append(player) # this table.
# Get a list of all the other players on this table
others = redis.zrange(self.players_key, 0, -1)
# Check if the player exists (race condition I guess)
score = redis.zscore(self.players_key, player.name)
if score is None:
# Add new player to the player list
redis.zadd(self.players_key, player.name, 0)
# Add player to the turn list if he/she wasn't already there
redis.zadd(self.turns_key, player.name, time.time())
# Prepare joined messages for all existing players
msgs = []
for other in others:
if other == player.name:
continue
msg = Message('JOINED')
msg.player_name = other
msgs.append(msg)
# Prepare passed message to set correct turn
current = self._get_artist()
msg = Message('PASSED', player_name=current)
if player.name == current:
msg.word = redis.get(self.word_key)
end_time = time.time() + 120
if not redis.setnx(self.end_key, end_time):
# Clock's already started!
end_time = redis.get(self.end_key)
else:
end_time = redis.get(self.end_key)
assert(end_time is not None)
msg.end_time = end_time
msgs.append(msg)
# Send all the prepared messages
gevent.joinall([gevent.spawn(player.send, x) for x in msgs])
示例9: hello
def hello():
# to_store = read_tags()
# to_store.append('test tag not on MER')
# redis.delete('allTags')
# for tag in to_store:
# redis.rpush('allTags', tag)
hint = redis.get('hint').decode('utf-8')
sol = redis.get('sol').decode('utf-8')
stored_tags = redis.lrange('allTags', 0, -1)
MER_tags = read_tags()
not_on_MER = [item for item in stored_tags if item not in MER_tags]
return render_template("communicate.html",
myhint=hint, mysol=sol, tags=MER_tags, tags_not_on_MER=not_on_MER)
示例10: test
def test():
r = requests.get('http://localhost:8000/products/ProductItems')
print r.text
data = json.loads(r.text)
lost = []
for rfid in data:
cur = rfid['RFID']
if redis.get(cur) == None:
print 'lost',cur
lost.append(cur)
redis.set('lost', lost)
print redis.get('lost')
示例11: getlatest
def getlatest(request):
global redis
int_fields = { 'ExcitementShortTerm', 'ExcitementLongTerm', 'FrustrationScore', 'LowerfaceValue', 'UpperfaceValue'}
js_dict = { f: int(round(100 * float(redis.get(f) or 0))) for f in int_fields }
str_fields = {'Lowerface', 'Upperface'}
js_dict.update( {f: redis.get(f) for f in str_fields} )
#create data
print js_dict
return js_dict
示例12: _listen_worker
def _listen_worker(self, channel_id, factory, processor):
connection = redis.Redis(*self.address)
self._create_channel(connection, channel_id)
collection = connection[self._db][channel_id]
cursor = redis.sort((redis.get("_id"),("_id", ASC)))
while True:
for envelope in cursor.interkeys():
msg = take_from_envelope(envelope, factory)
processor.process(envelope[FROM_FIELD], envelope[TO_FIELD], channel_id, msg);
collection.update({"_id": envelope["_id"]}, {"$set": {READ_FIELD: True}})
self._sleep(0.05)
cursor = redis.sort((redis.get(TO_FIELD: self.get_id())),("_id", ASC))
示例13: create_report
def create_report(redis, id, name, email):
print "%s <%s>/%d" % (name, email, id)
# Gather data
hits = int(redis.get('hit:%s' % id) or '0')
hps = int(redis.get('honeypot:%s' % id) or '0')
print " %d of %d blocked" % (hits-hps, hits)
if hits > 0:
send_report(name, email, hits, hps)
# Clear processed data
redis.decr('hit:%s' % id, hits)
redis.decr('honeypot:%s' % id, hps)
示例14: hello
def hello():
selbots = [];
for key in sorted(["host:DevSystem0.local","host:DevSystem1.local","host:DevSystem2.local","host:DevSystem3.local"]):
if (redis.get(key)):
s = json.loads(redis.get(key))
# time in seconds since epoch as int
now = int(time.time())
mins = (now - s['time']) / 60;
rel = natural.date.delta(now, s['time'], words=False)
s['server'] = key
s['minutes_ago'] = mins
s['time_ago_relative'] = rel[0]
selbots.append(s)
return render_template('house.html', servers=selbots)
示例15: done
def done():
id = request.form.get('id', None)
if id:
return redis.get(id.split('.gif')[0])
else:
return 'error'