本文整理汇总了Python中redis.StrictRedis.hmset方法的典型用法代码示例。如果您正苦于以下问题:Python StrictRedis.hmset方法的具体用法?Python StrictRedis.hmset怎么用?Python StrictRedis.hmset使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类redis.StrictRedis
的用法示例。
在下文中一共展示了StrictRedis.hmset方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: send_friend_request
# 需要导入模块: from redis import StrictRedis [as 别名]
# 或者: from redis.StrictRedis import hmset [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
示例2: RedisJobStore
# 需要导入模块: from redis import StrictRedis [as 别名]
# 或者: from redis.StrictRedis import hmset [as 别名]
class RedisJobStore(JobStore):
def __init__(self, db=0, key_prefix="jobs.", pickle_protocol=pickle.HIGHEST_PROTOCOL, **connect_args):
self.jobs = []
self.pickle_protocol = pickle_protocol
self.key_prefix = key_prefix
if db is None:
raise ValueError('The "db" parameter must not be empty')
if not key_prefix:
raise ValueError('The "key_prefix" parameter must not be empty')
self.redis = StrictRedis(db=db, **connect_args)
def add_job(self, job):
job.id = str(uuid4())
job_state = job.__getstate__()
job_dict = {
"job_state": pickle.dumps(job_state, self.pickle_protocol),
"runs": "0",
"next_run_time": job_state.pop("next_run_time").isoformat(),
}
self.redis.hmset(self.key_prefix + job.id, job_dict)
self.jobs.append(job)
def remove_job(self, job):
self.redis.delete(self.key_prefix + job.id)
self.jobs.remove(job)
def load_jobs(self):
jobs = []
keys = self.redis.keys(self.key_prefix + "*")
pipeline = self.redis.pipeline()
for key in keys:
pipeline.hgetall(key)
results = pipeline.execute()
for job_dict in results:
job_state = {}
try:
job = Job.__new__(Job)
job_state = pickle.loads(job_dict["job_state".encode()])
job_state["runs"] = long(job_dict["runs".encode()])
dateval = job_dict["next_run_time".encode()].decode()
job_state["next_run_time"] = datetime.strptime(dateval, "%Y-%m-%dT%H:%M:%S")
job.__setstate__(job_state)
jobs.append(job)
except Exception:
job_name = job_state.get("name", "(unknown)")
logger.exception('Unable to restore job "%s"', job_name)
self.jobs = jobs
def update_job(self, job):
attrs = {"next_run_time": job.next_run_time.isoformat(), "runs": job.runs}
self.redis.hmset(self.key_prefix + job.id, attrs)
def close(self):
self.redis.connection_pool.disconnect()
def __repr__(self):
return "<%s>" % self.__class__.__name__
示例3: IndexCache
# 需要导入模块: from redis import StrictRedis [as 别名]
# 或者: from redis.StrictRedis import hmset [as 别名]
class IndexCache(object):
def __init__(self, host, port):
self.client = StrictRedis(host=host, port=port, db=0)
def build(self, doc_word_scores):
"""Clears the entire store and adds all the doc_word_scores into a
hash table in the store.
:param doc_word_scores: dictionary of dictionaries that looks like:
doc_word_scores[word][doc_id] = score of word in that
document
"""
self.reset()
for word, doc_id_score in doc_word_scores.items():
# Add table name to word
word_key = DOCUMENT_WORD_SCORE_NAME + word
self.client.hmset(word_key, doc_id_score)
self.save_to_disk()
def reset(self):
"""Deletes all keys in this DB.
"""
self.client.flushdb()
def save_to_disk(self):
"""Asyncronous write to disk for persistent storage.
"""
self.client.bgsave()
def to_dict(self):
"""Returns the "doc_word_scores" table in Redis in dictionary form.
"""
doc_word_scores = {}
for word_key in self.doc_word_scores_iter():
# Remove the table name from the key
word = word_key.replace(DOCUMENT_WORD_SCORE_NAME, "")
# Grab the {doc_ids : scores} dictionary for word
doc_word_scores[word] = self.client.hgetall(word_key)
return doc_word_scores
def doc_word_scores_iter(self):
"""Returns an iterator for the keys of all the words stored in Redis
"""
return self.client.scan_iter(match=DOCUMENT_WORD_SCORE_NAME + "*")
def is_empty(self):
return self.client.dbsize() <= 0
def doc_scores(self, word):
"""Returns a hash table of document_ids mapping to scores
"""
word_key = DOCUMENT_WORD_SCORE_NAME + word
return self.client.hgetall(word_key)
示例4: new_group
# 需要导入模块: from redis import StrictRedis [as 别名]
# 或者: from redis.StrictRedis import hmset [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})
示例5: main
# 需要导入模块: from redis import StrictRedis [as 别名]
# 或者: from redis.StrictRedis import hmset [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)
示例6: CachedIDTClient
# 需要导入模块: from redis import StrictRedis [as 别名]
# 或者: from redis.StrictRedis import hmset [as 别名]
class CachedIDTClient(IDTClient):
def __init__(self, REDIS_HOST='localhost', REDIS_PORT=6379, REDIS_DB=0):
super(CachedIDTClient, self).__init__()
self.r = StrictRedis(REDIS_HOST, REDIS_PORT, REDIS_DB)
def get_info(self, sequence, oligo=2, na=40, mg=2, dntp=0.2):
if not self.r.exists(sequence):
tm = super(CachedIDTClient, self).get_melting_temp(sequence, oligo, na, mg, dntp)
dimer = super(CachedIDTClient, self).self_dimer_check(sequence)
info = {'tm': tm.tm, 'dimer': dimer.self_dimer, 'compPercent': dimer.compPercent}
self.r.hmset(sequence, info)
else:
info = self.r.hgetall(sequence)
return info
示例7: RedisBroker
# 需要导入模块: from redis import StrictRedis [as 别名]
# 或者: from redis.StrictRedis import hmset [as 别名]
class RedisBroker(object):
def __init__(self, **redis_c):
self.ip_set_name = redis_c.pop('ip_set_name')
self._r = StrictRedis(**redis_c)
def ip_notebook(self, ip):
(count, status) = self._r.hmget(ip, 'count', 'status')
print count, status
if not count:
self._r.hmset(ip, {'count': 1, 'status': 0})
self._r.sadd(self.ip_set_name, ip)
else:
self._r.hincrby(ip, 'count', amount=1)
示例8: write
# 需要导入模块: from redis import StrictRedis [as 别名]
# 或者: from redis.StrictRedis import hmset [as 别名]
def write(obj, **kwargs):
"""
Write a value in to loader source
:param obj: settings object
:param kwargs: vars to be stored
:return:
"""
client = StrictRedis(**obj.REDIS_FOR_DYNACONF)
holder = "DYNACONF_%s" % obj.DYNACONF_NAMESPACE
data = {
key.upper(): unparse_conf_data(value)
for key, value in kwargs.items()
}
client.hmset(holder.upper(), data)
load(obj)
示例9: Redis
# 需要导入模块: from redis import StrictRedis [as 别名]
# 或者: from redis.StrictRedis import hmset [as 别名]
class Redis(Backend):
"""Default backend for MimicDB. Initiated with identical parameters
as ``redis.StrictRedis``.
:param args \*args, \**kwargs: StrictRedis.__init__() parameters
.. code-block:: python
from mimicdb.backends.default import Redis
redis = Redis(host='localhost', port=6379, db=0)
"""
def __init__(self, *args, **kwargs):
self._redis = StrictRedis(*args, **kwargs)
def keys(self, pattern='*'):
return self._redis.keys(pattern)
def delete(self, *names):
return self._redis.delete(*names)
def sadd(self, name, *values):
return self._redis.sadd(name, *values)
def srem(self, name, *values):
return self._redis.srem(name, *values)
def sismember(self, name, value):
return self._redis.sismember(name, value)
def smembers(self, name):
return self._redis.smembers(name)
def hmset(self, name, mapping):
return self._redis.hmset(name, mapping)
def hgetall(self, name):
return self._redis.hgetall(name)
示例10: WikiController
# 需要导入模块: from redis import StrictRedis [as 别名]
# 或者: from redis.StrictRedis import hmset [as 别名]
class WikiController(object):
def __init__(self, settings):
"""Initialize the controler and preload basic metadata"""
self.redis = Redis(host=settings.redis.bind_address, port=settings.redis.port)
self.store = Store(settings.content.path)
self.get_all_pages() # page modification times
self.get_all_aliases() # page aliases
def get_page(self, path):
"""Returns a single page"""
if path in self.store.pages:
return self.store.get_page(path)
raise KeyError
def resolve_alias(self, path):
"""Attempts to resolve an alias to a page"""
# Check locally first, to save overhead
if path in self.store.aliases:
return self.store.aliases[path]
# Check if there's been an update in Redis
alias = self.redis.hget(META_ALIASES, path)
if alias:
self.store.aliases[path] = alias
return alias
return None
def get_all_pages(self):
"""Returns a hash of all known pages and mtimes"""
if not len(self.store.pages):
if self.redis.exists(META_PAGES):
self.store.pages = self.redis.hgetall(META_PAGES)
else:
# force filesystem scan and alias generation
pages = self.store.get_all_pages()
log.debug(pages)
self.redis.hmset(META_PAGES,self.store.get_all_pages())
return self.store.pages
def get_all_aliases(self):
"""Returns a hash of all known page aliases"""
if not len(self.store.aliases):
if self.redis.exists(META_ALIASES):
self.store.aliases = self.redis.hgetall(META_ALIASES)
else:
# force filesystem scan and alias generation
self.store.get_all_pages()
self.redis.hmset(META_ALIASES, self.store.aliases)
return self.store.aliases
def get_close_matches_for_page(self, path):
"""Get a list of close matches for a given page/path"""
pages = self.get_all_pages()
return get_close_matches(path, pages.keys())
示例11: JobsDB
# 需要导入模块: from redis import StrictRedis [as 别名]
# 或者: from redis.StrictRedis import hmset [as 别名]
class JobsDB(object):
prefix = { 'job' : 'multivac_job',
'log' : 'multivac_log',
'group' : 'multivac_group',
'action' : 'multivac_action',
'worker' : 'multivac_worker' }
def __init__(self, redis_host, redis_port):
self.redis = StrictRedis(
host=redis_host,
port=redis_port,
decode_responses=True)
self.subs = {}
# TODO: add connection test with r.config_get('port')
#######
# Job Methods
#######
def create_job(self, action_name, args=None, initiator=None):
"""
Create a new job with unique ID and subscribe to log channel
params:
- action_name(str): Name of the action this job uses
- args(str): Optional space-delimited series of arguments to be
appended to the job command
- initiator(str): Optional name of the user who initiated this job
"""
job = self.get_action(action_name)
if not job:
return (False, 'No such action')
#check that user has privilege for this command
if not self.check_user(initiator, job['allow_groups'].split(',')):
log.debug('action denied: %s for user %s' % \
(action_name, initiator))
return (False, 'Invalid user command')
job['id'] = str(uuid4().hex)
job['args'] = args
job['created'] = unix_time(datetime.utcnow())
if job['confirm_required'] == "True":
job['status'] = 'pending'
else:
job['status'] = 'ready'
self._subscribe_to_log(job['id'])
if initiator:
self.append_job_log(job['id'], 'Job initiated by %s' % initiator)
self.redis.hmset(self._key('job', job['id']), job)
return (True, job['id'])
def cancel_job(self, job_id):
""" Cancel and cleanup a pending job by ID """
job = self.get_job(job_id)
if job['status'] != 'pending':
return (False, 'Cannot cancel job in %s state' % job['status'])
self.cleanup_job(job_id, canceled=True)
return (True, '')
def update_job(self, job_id, field, value):
""" Update an arbitrary field for a job """
self.redis.hset(self._key('job', job_id), field, value)
return (True,)
def cleanup_job(self, job_id, canceled=False):
"""
Cleanup log subscriptions for a given job id and mark completed
params:
- canceled(bool): If True, mark job as canceled instead of completed
"""
logkey = self._key('log', job_id)
# send EOF signal to streaming clients
self.redis.publish(logkey, 'EOF')
if job_id in self.subs:
self.subs[job_id].unsubscribe()
del self.subs[job_id]
log.debug('Unsubscribed from log channel: %s' % logkey)
if canceled:
self.update_job(job_id, 'status', 'canceled')
else:
self.update_job(job_id, 'status', 'completed')
def get_job(self, job_id):
"""
Return single job dict given a job id
"""
return self.redis.hgetall(self._key('job', job_id))
#.........这里部分代码省略.........
示例12: __init__
# 需要导入模块: from redis import StrictRedis [as 别名]
# 或者: from redis.StrictRedis import hmset [as 别名]
class RespectfulRequester:
def __init__(self):
self.redis = StrictRedis(
host=config["redis"]["host"],
port=config["redis"]["port"],
password=config["redis"]["password"],
db=config["redis"]["database"])
try:
self.redis.echo("Testing Connection")
except ConnectionError:
raise RequestsRespectfulRedisError("Could not establish a connection to the provided Redis server")
def __getattr__(self, attr):
if attr in ["delete", "get", "head", "options", "patch", "post", "put"]:
return getattr(self, "_requests_proxy_%s" % attr)
else:
raise AttributeError()
@property
def redis_prefix(self):
return "RespectfulRequester"
def request(self, request_func, realms, wait=False):
if not isinstance(realms, Sequence) or isinstance(realms, basestring):
realms = [realms]
for realm in realms:
if realm not in self.fetch_registered_realms():
raise RequestsRespectfulError("Realm '%s' hasn't been registered" % realm)
if wait:
while True:
try:
return self._perform_request(request_func, realms)
except RequestsRespectfulRateLimitedError:
pass
time.sleep(1)
else:
return self._perform_request(request_func, realms)
def fetch_registered_realms(self):
return list(map(lambda k: k.decode("utf-8"), self.redis.smembers("%s:REALMS" % self.redis_prefix)))
def register_realm(self, realm, max_requests, timespan):
redis_key = self._realm_redis_key(realm)
if not self.redis.hexists(redis_key, "max_requests"):
self.redis.hmset(redis_key, {"max_requests": max_requests, "timespan": timespan})
self.redis.sadd("%s:REALMS" % self.redis_prefix, realm)
return True
def update_realm(self, realm, **kwargs):
redis_key = self._realm_redis_key(realm)
updatable_keys = ["max_requests", "timespan"]
for updatable_key in updatable_keys:
if updatable_key in kwargs and type(kwargs[updatable_key]) == int:
self.redis.hset(redis_key, updatable_key, kwargs[updatable_key])
return True
def unregister_realm(self, realm):
self.redis.delete(self._realm_redis_key(realm))
self.redis.srem("%s:REALMS" % self.redis_prefix, realm)
request_keys = self.redis.keys("%s:REQUEST:%s:*" % (self.redis_prefix, realm))
[self.redis.delete(k) for k in request_keys]
return True
def realm_max_requests(self, realm):
realm_info = self._fetch_realm_info(realm)
return int(realm_info["max_requests".encode("utf-8")].decode("utf-8"))
def realm_timespan(self, realm):
realm_info = self._fetch_realm_info(realm)
return int(realm_info["timespan".encode("utf-8")].decode("utf-8"))
@classmethod
def configure(cls, **kwargs):
if "redis" in kwargs:
if type(kwargs["redis"]) != dict:
raise RequestsRespectfulConfigError("'redis' key must be a dict")
expected_redis_keys = ["host", "port", "password", "database"]
missing_redis_keys = list()
for expected_redis_key in expected_redis_keys:
if expected_redis_key not in kwargs["redis"]:
missing_redis_keys.append(expected_redis_key)
if len(missing_redis_keys):
raise RequestsRespectfulConfigError("'%s' %s missing from the 'redis' configuration key" % (
", ".join(missing_redis_keys),
"is" if len(missing_redis_keys) == 1 else "are"
))
#.........这里部分代码省略.........
示例13: StrictRedis
# 需要导入模块: from redis import StrictRedis [as 别名]
# 或者: from redis.StrictRedis import hmset [as 别名]
try:
redis_connection = StrictRedis(host=HOST_FOR_TESTING, port=6379, db=2)
except ConnectionError as ce:
print("Unable to connect to {}. Error: {}".format(HOST_FOR_TESTING, ce))
# If we have a connection to Redis, wait 15 seconds and add a rule
if redis_connection is not None:
print("Giving you 15 seconds so you can start tailing the logs")
sleep(15)
# Collect on tweets with the keyword `python`
# Change the rule value if you want to collect on a different keyword or hashtag. Go nuts!
test_track_rule = {
"tag": "Traptor.Test",
"type": "track",
"value": "python",
"description": "Test track rule for python"
}
try:
redis_key = "traptor-{}:{}:{}".format(TRAPTOR_TYPE, TRAPTOR_ID, 123)
redis_connection.hmset(redis_key, test_track_rule)
print("Rule added")
print("Redis Key: {}".format(redis_key))
print("Rule: {}".format(test_track_rule))
except ConnectionError as ce:
print("Unable to add rule to Redis: {}".format(ce))
示例14: RedisJobStore
# 需要导入模块: from redis import StrictRedis [as 别名]
# 或者: from redis.StrictRedis import hmset [as 别名]
class RedisJobStore(JobStore):
def __init__(self, db='apscheduler', key_prefix='jobs.',
pickle_protocol=pickle.HIGHEST_PROTOCOL, **connect_args):
self.jobs = []
self.pickle_protocol = pickle_protocol
self.key_prefix = key_prefix
if not db:
raise ValueError('The "db" parameter must not be empty')
if not key_prefix:
raise ValueError('The "key_prefix" parameter must not be empty')
self.redis = StrictRedis(db=db, **connect_args)
def add_job(self, job):
job.id = str(uuid4())
job_state = job.__getstate__()
job_dict = {
'job_state': pickle.dumps(job_state, self.pickle_protocol),
'runs': '0',
'next_run_time': job_state.pop('next_run_time').isoformat()}
self.redis.hmset(self.key_prefix + job.id, job_dict)
self.jobs.append(job)
def remove_job(self, job):
self.redis.delete(self.key_prefix + job.id)
self.jobs.remove(job)
def load_jobs(self):
jobs = []
keys = self.redis.keys(self.key_prefix + '*')
pipeline = self.redis.pipeline()
for key in keys:
pipeline.hgetall(key)
results = pipeline.execute()
for job_dict in results:
job_state = {}
try:
job = Job.__new__(Job)
job_state = pickle.loads(job_dict['job_state'.encode()])
job_state['runs'] = long(job_dict['runs'.encode()])
dateval = job_dict['next_run_time'.encode()].decode()
job_state['next_run_time'] = datetime.strptime(
dateval, '%Y-%m-%dT%H:%M:%S')
job.__setstate__(job_state)
jobs.append(job)
except Exception:
job_name = job_state.get('name', '(unknown)')
logger.exception('Unable to restore job "%s"', job_name)
self.jobs = jobs
def update_job(self, job):
attrs = {
'next_run_time': job.next_run_time.isoformat(),
'runs': job.runs}
self.redis.hmset(self.key_prefix + job.id, attrs)
def close(self):
self.redis.connection_pool.disconnect()
def __repr__(self):
return '<%s>' % self.__class__.__name__
示例15: StrictRedis
# 需要导入模块: from redis import StrictRedis [as 别名]
# 或者: from redis.StrictRedis import hmset [as 别名]
ch = logging.StreamHandler()
fmt = logging.Formatter("%(levelname)s %(threadName)s %(message)s")
ch.setFormatter(fmt)
logger.addHandler(ch)
# Clear existing next hop key in Redis
redis_conn = StrictRedis()
nh_key = "NIROUTER/GET_FWD/nh"
redis_conn.delete(nh_key)
# Put some entries in the next hop database
nhl = {}
nhl[0] = "tcd.netinf.eu"
nhl[1] = "dtn://mightyatom.dtn"
nhl[2] = "tcd-nrs.netinf.eu"
redis_conn.hmset(nh_key, nhl)
ndo_cache = TestCache()
gw = DtnHttpGateway( None, logger, ndo_cache, redis_conn, None)
gw.start_gateway()
time.sleep(0.1)
test_run_length = 200.0
logger.info("Gateway running - will run for %f secs or until Ctrl/C" %
test_run_length)
test_run = True
def end_test():
global test_run
test_run = False
gw.shutdown_gateway()