本文整理汇总了Python中redis.StrictRedis.expire方法的典型用法代码示例。如果您正苦于以下问题:Python StrictRedis.expire方法的具体用法?Python StrictRedis.expire怎么用?Python StrictRedis.expire使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类redis.StrictRedis
的用法示例。
在下文中一共展示了StrictRedis.expire方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: post
# 需要导入模块: from redis import StrictRedis [as 别名]
# 或者: from redis.StrictRedis import expire [as 别名]
def post(self, request):
course_code = request.POST.get('course_code')
duration = int(request.POST.get('duration'))
r = StrictRedis(host='localhost', port=6379, db=0)
r.set('{}{}'.format(self.redis_key, course_code), course_code)
r.expire('{}{}'.format(self.redis_key, course_code), duration*3600)
return Response({'success': 'active_class stored'})
#def get_client_ip(request):
# x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
# if x_forwarded_for:
# ip = x_forwarded_for.split(',')[-1].strip()
# else:
# ip = request.META.get('REMOTE_ADDR')
# return ip
#or django-ipaware
示例2: feed_db
# 需要导入模块: from redis import StrictRedis [as 别名]
# 或者: from redis.StrictRedis import expire [as 别名]
def feed_db(container_id, stats):
""" Store data to Redis.
args:
- constainer_id : (str) container's hash 12 first characters
- stats : a dictionary of stats
"""
if DEBUG:
print('feed db with container {} stats'.format(container_id))
# convert the time provided by stats to UTC format, parse it with strptime,
# and transform it again to the desired REDIS_KEY_TIMESTAMP format
instant_str = stats['read'][:-9]+stats['read'][-6:].replace(':', '')
instant = datetime.strptime(instant_str, '%Y-%m-%dT%H:%M:%S.%f%z')
timestamp = instant.strftime(REDIS_KEY_TIMESTAMP)
r = StrictRedis(host=REDIS_HOST, port=REDIS_PORT, db=REDIS_DB)
for resource, value in stats.items():
if resource != 'read':
key = REDIS_KEY.format(timestamp=timestamp,
container_id=container_id,
resource=resource)
r.set(key, dumps(value))
r.expire(key, REDIS_EXPIRE_TIME)
if DEBUG:
print("Stored {} => {}".format(key, value))
示例3: main
# 需要导入模块: from redis import StrictRedis [as 别名]
# 或者: from redis.StrictRedis import expire [as 别名]
def main():
r = StrictRedis()
key = datetime.now().strftime('%Y.%m.%d.%H.%m')
r.hmset('toaster.%s' % key, download_data())
# Expire slightly over 24 hours, just in case
r.expire('toaster.%s' % key, 60 * 60 * 25)
示例4: post
# 需要导入模块: from redis import StrictRedis [as 别名]
# 或者: from redis.StrictRedis import expire [as 别名]
def post(self, request):
course_code = request.POST.get('course_code')
duration = int(request.POST.get('duration'))
r = StrictRedis(host='localhost', port=6379, db=0)
r.set('{}{}'.format(self.redis_key, course_code), course_code)
r.expire('{}{}'.format(self.redis_key, course_code), duration*3600)
return Response({'success': 'active_class stored'})
示例5: WatchmanBlacklist
# 需要导入模块: from redis import StrictRedis [as 别名]
# 或者: from redis.StrictRedis import expire [as 别名]
class WatchmanBlacklist(object):
def __init__(self, config_xml = None):
if config_xml is None:
config_xml = ET.parse(CONFIG_FILE)
#elif not isinstance(config_xml,ET.Element) and not isinstance(config_xml,ET.ElementTree):
# raise TypeError("config_xml must be either None or an ElementTree element")
try:
password = config_xml.find('/global/password').text
except StandardError as e:
password = ""
try:
redishost = config_xml.find('/global/redis').text
except StandardError as e:
redishost = "localhost"
try:
expire = config_xml.find('/global/expire').text
self.expire = int(expire)
except StandardError as e:
logging.warning("No <expire> setting in the <global> section of config. Defaulting to 360s.")
self.expire = 360
try:
dbnum = config_xml.find('/global/blacklistdb').text
self._dbnum = int(dbnum)
except StandardError as e:
logging.warning("No blacklistdb setting in the <global> section of config. Defaulting to Redis database 2.")
dbnum = 2
self._conn = StrictRedis(host=redishost, password=password, db=dbnum)
def get(self,filepath,update=True,value="(locked)"):
"""
Check if the given path is in the blacklist, and optionally update the lock whether or not it exists
:param filepath: file path to check
:param update: if True, then add the filepath to the blacklist and reset the expiry counter - even if it already exists.
:param value: value to store against the file path (typically the mtime)
:return: value of the key or None
"""
rtn = self._conn.get(filepath)
#if update:
# self._conn.setnx(filepath, value)
# self._conn.expire(filepath, self.expire)
if not self._conn.exists(filepath):
logging.debug("{0} does not exist in the blacklist. Attempting to add it.".format(filepath))
self._conn.setnx(filepath, value)
self._conn.expire(filepath, self.expire)
return rtn
示例6: update_status
# 需要导入模块: from redis import StrictRedis [as 别名]
# 或者: from redis.StrictRedis import expire [as 别名]
def update_status(msg, **redis_kwargs):
""" Updated Redis with a message, prefix it with the current timestamp.
Keyword args are passed directly to redis.StrictRedis().
"""
pid = getpid()
red = StrictRedis(**redis_kwargs)
key = 'pid-%d-statuses' % pid
msg = '%.6f %s' % (time(), msg)
red.lpush(key, msg)
red.expire(key, 60 * 60)
red.ltrim(key, 0, _keep)
示例7: view_user_json
# 需要导入模块: from redis import StrictRedis [as 别名]
# 或者: from redis.StrictRedis import expire [as 别名]
def view_user_json(username):
"""The twitter user JSON view"""
username = username.lower()
redis_key = "%s.user.%s" % (REDIS_PREFIX, username)
redis = StrictRedis()
cache = redis.get(redis_key)
if not cache:
cache = dict(status='queued', header='Queued',
message="Your request will be processed shortly",
code=200)
redis.set(redis_key, dumps(cache))
redis.expire(redis_key, CACHE_HOURS*60*60)
load_tweets.delay(username)
sleep(.5)
cache = loads(redis.get(redis_key))
return jsonify(cache)
示例8: RedisManager
# 需要导入模块: from redis import StrictRedis [as 别名]
# 或者: from redis.StrictRedis import expire [as 别名]
class RedisManager(NoSqlManager):
def __init__(self, namespace, url=None, data_dir=None, lock_dir=None, **params):
self.expiretime = params.pop('expiretime', None)
NoSqlManager.__init__(self, namespace, url=url, data_dir=data_dir, lock_dir=lock_dir, **params)
def open_connection(self, host, port, **params):
self.db_conn = StrictRedis(host=host, port=int(port), **params)
def __getitem__(self, key):
return pickle.loads(self.db_conn.hget(self._format_key(key), 'data'))
def __contains__(self, key):
return self.db_conn.exists(self._format_key(key))
def set_value(self, key, value, expiretime=None):
key = self._format_key(key)
#
# beaker.container.Value.set_value calls NamespaceManager.set_value
# however it (until version 1.6.4) never sets expiretime param.
#
# Checking "type(value) is tuple" is a compromise
# because Manager class can be instantiated outside container.py (See: session.py)
#
if (expiretime is None) and (type(value) is tuple):
expiretime = value[1]
self.db_conn.hset(key, 'data', pickle.dumps(value))
self.db_conn.hset(key, 'accessed', datetime.now())
self.db_conn.hsetnx(key, 'created', datetime.now())
if expiretime or self.expiretime:
self.db_conn.expire(key, expiretime or self.expiretime)
def __delitem__(self, key):
self.db_conn.delete(self._format_key(key))
def _format_key(self, key):
return 'beaker:%s:%s' % (self.namespace, key.replace(' ', '\302\267'))
def do_remove(self):
self.db_conn.flushdb()
def keys(self):
return self.db_conn.keys('beaker:%s:*' % self.namespace)
示例9: index
# 需要导入模块: from redis import StrictRedis [as 别名]
# 或者: from redis.StrictRedis import expire [as 别名]
def index(lang, degree, loc):
r = StrictRedis(host='localhost', port=6379, db=0)
hash_sum = "h" + md5("{0}/{1}/{2}".format(lang, degree, loc)).hexdigest()
if r.exists(hash_sum):
return r.get(hash_sum)
weather, weather_dict = weather_data(lang, degree, loc)
temp = temp_now = float(weather_dict["weather_now"]["temp"])
if degree == "F":
temp_now = (temp_now - 32)*5.0/9
result = dumps({
"weather": weather,
"links": links(lang),
"surfaces": surfaces(lang, temp_now),
"feedback": {"current_temp": str(int(temp)),
"sensation_desc": vote_sensation_list(lang),
"list_surfaces": all_surface(lang)}})
r.set(hash_sum, result)
r.expire(hash_sum, 600)
return result
示例10: RedisCache
# 需要导入模块: from redis import StrictRedis [as 别名]
# 或者: from redis.StrictRedis import expire [as 别名]
class RedisCache(AbstractCache, Loggable):
"""A cache backed by Redis
Use as a dictionary,
>>> cache = RedisCache(host="localhost", port=6379)
>>> cache['hello'] = 'world'
>>> cache['hello'] # 'world'
>>> 'hello' in cache # True
>>> 'goodbye' in cache # False
or as a function memoizer,
>>> @cache.memoize
>>> def hello(name):
... return "Hello, " + name
Parameters
----------
same as `redis.StrictRedis`
"""
def __init__(self, *args, **kwargs):
AbstractCache.__init__(self, kwargs.get('timeout', datetime.timedelta(days=1)))
Loggable.__init__(self)
if 'timeout' in kwargs:
del kwargs['timeout']
self.redis = StrictRedis(*args, **kwargs)
def get(self, key):
# value will be None if key is missing, but this is ambiguous
value = self.redis.get(key)
if not self.redis.exists(key):
raise KeyError()
else:
return pickle.loads(value)
def set(self, key, value, timeout=None):
self.redis.set(key, pickle.dumps(value))
self.redis.expire(key, datetime.timedelta(seconds=timeout) or self.timeout)
示例11: ItemViewsTest
# 需要导入模块: from redis import StrictRedis [as 别名]
# 或者: from redis.StrictRedis import expire [as 别名]
#.........这里部分代码省略.........
self.assertEqual(DBSession.query(Item).count(), 0)
def test_upload_item_images_post_uuid(self):
"""
Test posting images for an item via uuid.
"""
self._create_item_status()
item = Item(name='iPhone', type='TRADE', quantity=1,
description='A smart phone', status=self.draft_status,
reason='just because')
DBSession.add(item)
DBSession.commit()
item_uuid = str(uuid.uuid4())
mock_image = MockFileImage('image1.png')
# write to disk the dummy image so the view can resize it
original = '%s.png' % item_uuid
static_path = pkgr.resource_filename('tradeorsale', 'static')
image_path = os.path.join(static_path,
os.path.join('items/images', str(item.id)), original)
with open(image_path, 'wb') as handle:
handle.write(mock_image.file.read())
self.failUnless(os.path.exists(image_path))
# build request
mock_image.file.seek(0)
payload = {"uuid": item_uuid, "image": mock_image}
request = testing.DummyRequest(post=payload)
request.registry = self.config.registry
# set a dummy uuid to regis
self.redis.hset('item_uuid_to_id', item_uuid, item.id)
self.redis.expire(item_uuid, 3600)
response = upload_item_images(request)
self.assertEqual(response.status_code, 200)
# test that there are 3 images: original, small and medium
self.assertEqual(DBSession.query(ItemImage).filter_by(item_id=item.id).count(), 3)
def test_upload_item_images_post_uuid_failed(self):
"""
Test posting images for an item via uuid with invalid image fails.
"""
self._create_item_status()
item = Item(name='iPhone', type='TRADE', quantity=1,
description='A smart phone', status=self.draft_status,
reason='just because')
DBSession.add(item)
DBSession.commit()
class DumbMockImage(object):
file = StringIO('image')
filename = 'image1.jpg'
item_uuid = str(uuid.uuid4())
mock_image = DumbMockImage()
payload = {"uuid": item_uuid, "image": mock_image}
request = testing.DummyRequest(post=payload)
request.registry = self.config.registry
# set a dummy uuid to regis
self.redis.hset('item_uuid_to_id', item_uuid, item.id)
self.redis.expire(item_uuid, 3600)
示例12: start_competition
# 需要导入模块: from redis import StrictRedis [as 别名]
# 或者: from redis.StrictRedis import expire [as 别名]
def start_competition(request,groupname):
# prepare the game
# now set the questions here!
'''
ok so the new idea is to delete the group entry
so that the ginfo won't come to know about this
group, so that means every thing related to the
group will be deleted, after storing it to the database
so the set element in pref:groups need to be deleted
then pref:groupname:hash needs to be deleted
but pref:groupname:wordpks need to be added, with
a expire timeout of say 5 seconds, though it is too much
chuck that, how about setting the expire timeout here
and then copy every property of hash ...
actually only pref:groups entry has to be deleted because
using this set, ginfo accesses the hash.
lets set the time out here for the hash
and also broadcast this to inform that a group was deleted
maybe settings message.type == 'group_delete'
'''
print "starting the competition for "+groupname
print 'the following keys are there'
rd = StrictRedis()
pref = settings.MY_PREFIX
prefg = pref+":"+groupname
d = rd.hgetall(prefg+":hash")
print rd.keys(pref+'*')
print "changing from ",d
totwords = int(d['totwords'])
wordpks = random.sample([x for x in range(1,31)], totwords)
wordpks = '-'.join([str(x) for x in wordpks])
rd.hset(prefg+":hash", 'wordpks', wordpks)
print "to",rd.hgetall(prefg+":hash")
redis_publisher = RedisPublisher(facility = groupname, broadcast = True)
message = RedisMessage('#start')
redis_publisher.publish_message(message)
print "published the #start"
# rd.expire(prefg+":hash", extime) # get rid of the group details after extime seconds
# rd.expire(pref+":"+groupname, extime) # don't require the usernames in that group also
'''
don't do the expire here, do it in ganswer_post:
whenever user requests the wordpks, it removes its username from pref:groupname.
so check if llen('pref:groupname) is one then remove both, hash and this set
this way we will be sure that only delete when every user has transferred wordpks from redis to session
'''
rd.srem(pref+":groups", groupname) # prevent this group from showing up in the ginfo
# to be on the safer side, should i create a new key storing wordpks? prefg:wordpks?
group_members = rd.smembers(prefg)
rd.sadd(prefg+":members", *group_members)
rd.sadd(prefg+":gmembers", *group_members)
rd.expire(prefg+":gmembers", 500)
# create a new key containing all the members of this group
# in pref:groupname:members this key will be helpful in checking
# how many users have completed the competition, on similar lines
# pref:groupname key will be responsible in providing the condition
# as to when the pref:groupname:hash need to be deleted!
# also copying to gmembers so that i know whose results are to be delivered in result_group
# but only for 5 minutes you can view your previous group results, restricted, right? i know
# the idea is to make a generic view which returns all the information, pretty much like
# the admin interface app but providing interactive charts rather than pure data to see
print "copied the group_members",group_members
redis_publisher = RedisPublisher(facility = pref, broadcast = True)
delete_group_msg = json.dumps({'type':'group_busy', 'name':groupname})
redis_publisher.publish_message(RedisMessage(delete_group_msg))
sttime=datetime.now()
usrs=rd.smembers(prefg)
print "for",groupname,"members are",usrs
for i in usrs:
obj=GroupFinalResult(re_user=User.objects.get(username=i),groupname=groupname,marks=0,starttime=sttime,endtime=sttime)
obj.save()
print 'leaving start competition...'
print rd.keys(pref+"*")
示例13: KeyValueStore
# 需要导入模块: from redis import StrictRedis [as 别名]
# 或者: from redis.StrictRedis import expire [as 别名]
class KeyValueStore(object):
def __init__(self):
self.data = StrictRedis(host = settings.redis.server.host, port = settings.redis.server.port)
log.debug("Connected to REDIS(%s, %s)" % (settings.redis.server.host, settings.redis.server.port))
def _get_value(self, key):
return self.data.get(key)
def _set_value(self, key, value, seconds=None):
self.data.set(key, value)
if seconds is not None:
self.data.expire(key, seconds)
def _delete_key(self, key):
self.data.delete(key)
def _search_keys(self, pattern):
return self.data.keys(pattern)
def _get_model(self, model_pf, model_id):
value = self._get_value(model_pf+model_id)
if value is None:
return None
return Struct(loads(self._get_value(model_pf+model_id)))
def _set_model(self, model_pf, model_id, model_value, seconds=None):
self._set_value(model_pf+model_id, dumps(model_value, default=datetime_serializer), seconds)
def _list_model(self, model_pf):
return [Struct(loads(self._get_value(key))) for key in self._search_keys(model_pf+'*')]
def _get_list_models(self, list_pf, list_id):
return [Struct(loads(value)) for value in self.data.lrange(list_pf+list_id, 0, -1)]
def _get_list_scalars(self, list_pf, list_id):
return [value for value in self.data.lrange(list_pf+list_id, 0, -1)]
def _pop_list_scalars(self, list_pf, list_id):
scalars = []
scalar = True
while scalar:
scalar=self.data.lpop(list_pf+list_id)
if scalar:
scalars += [scalar]
return scalars
def _push_list(self, list_pf, list_id, model_value, trim_count):
if not isinstance(model_value, unicode):
model_value = dumps(model_value)
self.data.lpush(list_pf+list_id, model_value)
self.data.ltrim(list_pf+list_id, 0, MAX_STAT_ITEMS-1)
# Devices
def get_device(self, mac_address):
return self._get_model(DEVICE_PF, mac_address.replace(":","").upper())
def set_device(self, mac_address, device):
self._set_model(DEVICE_PF, mac_address.replace(":","").upper(), device)
def delete_device(self, mac_address):
self._delete_key(DEVICE_PF+mac_address.replace(":","").upper())
self._delete_key(ASSETLIST_PF+mac_address.replace(":","").upper())
def list_devices(self):
return self._list_model(DEVICE_PF)
# Assets
def get_asset(self, guid):
return self._get_model(ASSET_PF, guid)
def set_asset(self, guid, asset):
self._set_model(ASSET_PF, guid, asset)
def delete_asset(self, guid):
self._delete_key(ASSET_PF+guid)
def list_assets(self):
return self._list_model(ASSET_PF)
# Playlists
def get_playlist(self, name):
return self._get_model(PLAYLIST_PF, name)
def set_playlist(self, name, playlist):
self._set_model(PLAYLIST_PF, name, playlist)
def delete_playlist(self, name):
self._delete_key(PLAYLIST_PF+name)
def list_playlists(self):
return self._list_model(PLAYLIST_PF)
# Stats
#.........这里部分代码省略.........
示例14: Leaderboard
# 需要导入模块: from redis import StrictRedis [as 别名]
# 或者: from redis.StrictRedis import expire [as 别名]
#.........这里部分代码省略.........
to_dec = 0.0000000001
return float(value) + (ts * to_dec)
def _decode_value_with_time(self, combo):
from_dec = 10000000000
value = int(combo)
ts = (combo - value) * from_dec
if self.reverse == self.tie_oldest_wins:
ts = datetime.utcfromtimestamp(3000000000 - ts)
return value, ts
def _leaders_with_ranks(self, key, offset, end):
total = self.r.zcard(key)
l = self._range(key, offset, end)
if self.timed_ties:
l = [((m,) + self._decode_value_with_time(s)) for (m, s) in l]
else:
l = [(m, s, 0) for (m, s) in l]
log.info(l)
with_ranks = self._add_ranks(l, offset)
return total, with_ranks
def set_metric(self, user, value, ts=None):
"""
Set a new peak value for this user, e.g. high score
"""
if self.timed_ties:
value = self._encode_value_with_time(value, ts)
for r in self.ranges:
key = self._board_key(r)
self.r.zadd(key, value, user)
if r != self.RANGE_ALLTIME:
self.r.expire(key, r.expiration)
def inc_metric(self, user, value, ts=None):
"""
Increment the current value for this user, e.g. total earned
"""
if ts:
log.warn('inc_metric: timestamps not supported yet')
for r in self.ranges:
key = self._board_key(r)
self.r.zincrby(key, user, value)
if r != self.RANGE_ALLTIME:
self.r.expire(key, r.expiration)
def leaders(self, range, limit=-1, offset=0, id=None, slots_ago=0):
"""
Retrieve a list of global leaders.
:param range: The TimeRange to query
:param limit: Maximum number of entries to return
:param offset: Rank to start at, ignored if id is provided
:param id: Member to center the range of entries around, i.e. "leaders near me"
:param slots_ago: number of time slots prior, e.g. 1 for yesterday, last week, etc.
"""
key = self._board_key(range, slots_ago)
if id:
if self.reverse:
rank = self.r.zrevrank(key, id)
else:
rank = self.r.zrank(key, id)
log.debug('uid: %r, rank: %r', id, rank)
示例15: JobsDB
# 需要导入模块: from redis import StrictRedis [as 别名]
# 或者: from redis.StrictRedis import expire [as 别名]
#.........这里部分代码省略.........
ts = datetime.utcnow().strftime('%a %b %d %H:%M:%S %Y')
return json.dumps((ts, msg))
def _subscribe_to_log(self, job_id):
""" Subscribe this db object to a jobs log channel by ID """
key = self._key('log', job_id)
sub = self.redis.pubsub(ignore_subscribe_messages=True)
sub.subscribe(key)
self.subs[job_id] = sub
log.debug('Subscribed to log channel: %s' % key)
#######
# Action Methods
#######
def get_action(self, action_name):
"""
Return a single action dict, given the action name
"""
return self.redis.hgetall(self._key('action', action_name))
def get_actions(self):
"""
Return all configured actions
"""
return [self.redis.hgetall(k) for k in
self.redis.keys(pattern=self._key('action', '*'))]
def add_action(self, action):
self.redis.hmset(self._key('action', action['name']), action)
def purge_actions(self):
[self.redis.delete(k) for k in
self.redis.keys(pattern=self._key('action', '*'))]
#######
# Usergroup Methods
#######
def check_user(self, user, groups):
"""
Check a list of groups to see if a user is a member to any
params:
- user(str): user name
- groups(list): list of group names
"""
if 'all' in groups:
return True
for group in groups:
log.debug('checking group %s' % (group))
if user in self.get_group(group):
return True
return False
def get_group(self, group_name):
"""
Return a list of usernames belonging to a group
"""
return self.redis.lrange(self._key('group', group_name), 0, -1)
def get_groups(self):
"""
Return all configured groups
"""
key = self._key('group', '*')
groups = [ g.split(':')[1] for g in self.redis.keys(pattern=key) ]
return { g:self.get_group(g) for g in groups }
def add_group(self, group_name, members):
key = self._key('group', group_name)
for m in members:
self.redis.lpush(key, m)
def purge_groups(self):
[ self.redis.delete(k) for k in \
self.redis.keys(pattern=self._key('group', '*')) ]
#######
# Job Worker Methods
#######
def register_worker(self, name, hostname):
key = self._key('worker', name)
worker = {'name': name, 'host': hostname}
self.redis.hmset(key, worker)
self.redis.expire(key, 15)
def get_workers(self):
return [self.redis.hgetall(k) for k in
self.redis.keys(pattern=self._key('worker', '*'))]
#######
# Keyname Methods
#######
def _key(self, keytype, id):
return self.prefix[keytype] + ':' + id