本文整理汇总了Python中redis.StrictRedis方法的典型用法代码示例。如果您正苦于以下问题:Python redis.StrictRedis方法的具体用法?Python redis.StrictRedis怎么用?Python redis.StrictRedis使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类redis
的用法示例。
在下文中一共展示了redis.StrictRedis方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
# 需要导入模块: import redis [as 别名]
# 或者: from redis import StrictRedis [as 别名]
def __init__(self, io_loop: asyncio.AbstractEventLoop = None):
super().__init__()
self.io_loop = io_loop or asyncio.get_event_loop()
self.sub_client = self.io_loop.run_until_complete(
aioredis.create_redis((config.get('REDIS', 'host', fallback='localhost'),
config.getint('REDIS', 'port', fallback=6379)),
db=config.getint('REDIS', 'db', fallback=1)))
self.redis_client = redis.StrictRedis(
host=config.get('REDIS', 'host', fallback='localhost'),
db=config.getint('REDIS', 'db', fallback=1), decode_responses=True)
self.initialized = False
self.sub_tasks = list()
self.sub_channels = list()
self.channel_router = dict()
self.crontab_router = defaultdict(dict)
self.datetime = None
self.time = None
self.loop_time = None
示例2: __init__
# 需要导入模块: import redis [as 别名]
# 或者: from redis import StrictRedis [as 别名]
def __init__(self, name, host='localhost', port=6379, db=0,
maxsize=0, lazy_limit=True, password=None, cluster_nodes=None):
"""
Constructor for RedisQueue
maxsize: an integer that sets the upperbound limit on the number of
items that can be placed in the queue.
lazy_limit: redis queue is shared via instance, a lazy size limit is used
for better performance.
"""
self.name = name
if(cluster_nodes is not None):
from rediscluster import StrictRedisCluster
self.redis = StrictRedisCluster(startup_nodes=cluster_nodes)
else:
self.redis = redis.StrictRedis(host=host, port=port, db=db, password=password)
self.maxsize = maxsize
self.lazy_limit = lazy_limit
self.last_qsize = 0
示例3: reset_cached_search_results
# 需要导入模块: import redis [as 别名]
# 或者: from redis import StrictRedis [as 别名]
def reset_cached_search_results(project):
try:
redis_client = redis.StrictRedis(host=REDIS_SERVICE_HOSTNAME, socket_connect_timeout=3)
keys_to_delete = []
if project:
result_guids = [res.guid for res in VariantSearchResults.objects.filter(families__project=project)]
for guid in result_guids:
keys_to_delete += redis_client.keys(pattern='search_results__{}*'.format(guid))
else:
keys_to_delete = redis_client.keys(pattern='search_results__*')
if keys_to_delete:
redis_client.delete(*keys_to_delete)
logger.info('Reset {} cached results'.format(len(keys_to_delete)))
else:
logger.info('No cached results to reset')
except Exception as e:
logger.error("Unable to reset cached search results: {}".format(e))
示例4: __init__
# 需要导入模块: import redis [as 别名]
# 或者: from redis import StrictRedis [as 别名]
def __init__(self, policy_net, target_net, optimizer,
vis, replay_size=30000, hostname='localhost',
beta_decay=1000000,
use_memory_compress=False):
self._vis = vis
self._policy_net = policy_net
self._target_net = target_net
self._target_net.load_state_dict(self._policy_net.state_dict())
self._target_net.eval()
self._beta_decay = beta_decay
self._connect = redis.StrictRedis(host=hostname)
self._connect.delete('params')
self._optimizer = optimizer
self._win = self._vis.line(X=np.array([0]), Y=np.array([0]),
opts=dict(title='Memory size'))
self._win2 = self._vis.line(X=np.array([0]), Y=np.array([0]),
opts=dict(title='Q loss'))
self._memory = replay.Replay(replay_size, self._connect,
use_compress=use_memory_compress)
self._memory.start()
示例5: __init__
# 需要导入模块: import redis [as 别名]
# 或者: from redis import StrictRedis [as 别名]
def __init__(self, actor_no, env, policy_net, vis, hostname='localhost',
batch_size=50, nstep_return=3, gamma=0.999,
clip=lambda x: min(max(-1.0, x), 1.0),
target_update=200, num_total_actors=4,
device=torch.device("cuda" if torch.cuda.is_available() else "cpu")):
self._env = env
self._actor_no = actor_no
self._name = "actor_" + str(actor_no)
self._vis = vis
self._batch_size = batch_size
self._nstep_return = nstep_return
self._gamma = gamma
self._clip = clip
self._target_update = target_update
self._num_total_actors = num_total_actors
self._policy_net = policy_net
self._policy_net.eval()
self._device = device
self._win1 = self._vis.image(utils.preprocess(self._env.env._get_image()))
self._win2 = self._vis.line(X=np.array([0]), Y=np.array([0.0]),
opts=dict(title='Score %s' % self._name))
self._local_memory = replay_memory.ReplayMemory(1000)
self._connect = redis.StrictRedis(host=hostname)
示例6: _setup_redis
# 需要导入模块: import redis [as 别名]
# 或者: from redis import StrictRedis [as 别名]
def _setup_redis(self):
"""Returns a Redis Client"""
if not self.closed:
try:
self.logger.debug("Creating redis connection to host " +
str(self.settings['REDIS_HOST']))
self.redis_conn = redis.StrictRedis(host=self.settings['REDIS_HOST'],
port=self.settings['REDIS_PORT'],
db=self.settings['REDIS_DB'])
self.redis_conn.info()
self.redis_connected = True
self.logger.info("Successfully connected to redis")
except KeyError as e:
self.logger.error('Missing setting named ' + str(e),
{'ex': traceback.format_exc()})
except:
self.logger.error("Couldn't initialize redis client.",
{'ex': traceback.format_exc()})
raise
示例7: setup_once
# 需要导入模块: import redis [as 别名]
# 或者: from redis import StrictRedis [as 别名]
def setup_once():
# type: () -> None
import redis
patch_redis_client(redis.StrictRedis)
try:
import rb.clients # type: ignore
except ImportError:
pass
else:
patch_redis_client(rb.clients.FanoutClient)
patch_redis_client(rb.clients.MappingClient)
patch_redis_client(rb.clients.RoutingClient)
try:
_patch_rediscluster()
except Exception:
logger.exception("Error occured while patching `rediscluster` library")
示例8: init
# 需要导入模块: import redis [as 别名]
# 或者: from redis import StrictRedis [as 别名]
def init():
"""
Initialize key value store that will be used for the event publishing.
That way the main API takes advantage of Redis pub/sub capabilities to push
events to the event stream API.
"""
global socketio
try:
publisher_store = redis.StrictRedis(
host=host, port=port, db=redis_db, decode_responses=True
)
publisher_store.get("test")
socketio = SocketIO(message_queue=redis_url)
except redis.ConnectionError:
pass
return socketio
示例9: __init__
# 需要导入模块: import redis [as 别名]
# 或者: from redis import StrictRedis [as 别名]
def __init__(self, channel, address, port):
self.redis_client = redis.StrictRedis(host=address, port=port)
self.channel = channel
示例10: REDIS
# 需要导入模块: import redis [as 别名]
# 或者: from redis import StrictRedis [as 别名]
def REDIS(self):
return redis.StrictRedis(host="localhost", port=6379, db=0)
示例11: get_redis
# 需要导入模块: import redis [as 别名]
# 或者: from redis import StrictRedis [as 别名]
def get_redis():
if 'redis' not in __dbctx:
if config['redis'].get('unix_socket_path') is not None:
redis_client = redis.StrictRedis(
unix_socket_path=config['redis']['unix_socket_path'])
else:
redis_client = redis.StrictRedis(
host=config['redis']['host'], port=config['redis']['port'])
__dbctx['redis'] = redis_client
return __dbctx['redis']
# vim: ts=4 sw=4 sts=4 expandtab
示例12: is_trading_day
# 需要导入模块: import redis [as 别名]
# 或者: from redis import StrictRedis [as 别名]
def is_trading_day(day: datetime.datetime):
s = redis.StrictRedis(
host=config.get('REDIS', 'host', fallback='localhost'),
db=config.getint('REDIS', 'db', fallback=1), decode_responses=True)
return day, day.strftime('%Y%m%d') in (s.get('TradingDay'), s.get('LastTradingDay'))
# async with aiohttp.ClientSession() as session:
# await max_conn_cffex.acquire()
# async with session.get(
# 'http://{}/fzjy/mrhq/{}/index.xml'.format(cffex_ip, day.strftime('%Y%m/%d')),
# allow_redirects=False) as response:
# max_conn_cffex.release()
# return day, response.status != 302
示例13: setUp
# 需要导入模块: import redis [as 别名]
# 或者: from redis import StrictRedis [as 别名]
def setUp(self):
self.redis_client = redis.StrictRedis(
host=config.get('REDIS', 'host', fallback='localhost'),
db=config.getint('REDIS', 'db', fallback=1), decode_responses=True)
self.api = CTPTrader(io_loop=self.loop)
示例14: retry_connect
# 需要导入模块: import redis [as 别名]
# 或者: from redis import StrictRedis [as 别名]
def retry_connect(redis_cfg, tries=300, base_delay=4.):
for i in range(tries):
try:
r = redis.StrictRedis(**redis_cfg)
r.ping()
return r
except redis.ConnectionError as e:
if i == tries - 1:
raise
else:
delay = base_delay * (1 + (os.getpid() % 10) / 9)
logger.warning('Could not connect to {}. Retrying after {:.2f} sec ({}/{}). Error: {}'.format(
redis_cfg, delay, i + 2, tries, e))
time.sleep(delay)
示例15: test_basic
# 需要导入模块: import redis [as 别名]
# 或者: from redis import StrictRedis [as 别名]
def test_basic(self):
r = redis.StrictRedis()
r.set('foo', 'bar')
self.assertEquals(b'bar', r.get('foo'))