本文整理汇总了Python中django_redis.get_redis_connection方法的典型用法代码示例。如果您正苦于以下问题:Python django_redis.get_redis_connection方法的具体用法?Python django_redis.get_redis_connection怎么用?Python django_redis.get_redis_connection使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类django_redis
的用法示例。
在下文中一共展示了django_redis.get_redis_connection方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: create_clean
# 需要导入模块: import django_redis [as 别名]
# 或者: from django_redis import get_redis_connection [as 别名]
def create_clean(self):
"""
Creates a clean database
"""
self._log("Generating database...\n")
try:
has_data = Org.objects.exists()
except Exception: # pragma: no cover
raise CommandError("Run migrate command first to create database tables")
if has_data:
raise CommandError("Can't clean database over non-empty database. Did you mean to use --resume?")
# this is a new database so clear out redis
self._log("Clearing out Redis cache... ")
r = get_redis_connection()
r.flushdb()
self._log(self.style.SUCCESS("OK") + "\n")
superuser = User.objects.create_superuser("root", "root@nyaruka.com", USER_PASSWORD)
orgs = self.create_orgs(superuser, ORGS, GROUPS, FIELDS, PARTNERS, USER_PASSWORD)
self.create_contacts(orgs, 100)
return orgs
示例2: _save_views_to_db
# 需要导入模块: import django_redis [as 别名]
# 或者: from django_redis import get_redis_connection [as 别名]
def _save_views_to_db(view_keys, evict_from_cache=False):
if not view_keys:
return
redis = get_redis_connection('traffic_stats')
view_keys = [x.decode('utf-8') for x in view_keys]
for obj in view_keys:
model_name, model_id = obj.split(':')
if model_name in model_name_to_instance:
model = model_name_to_instance[model_name]
try:
instance = model.objects.get(id=model_id)
instance.view_count = redis.get(obj)
instance.save(update_fields=['view_count'])
except ObjectDoesNotExist:
log.warning('Tried to save views of non-existent instance.')
else:
log.warning(
'Tried to persist views of non-existent model ' + model_name
)
if evict_from_cache:
redis.delete(*view_keys)
log.info('Saved ' + str(view_keys))
示例3: test_freeze_user_final_grade_error2
# 需要导入模块: import django_redis [as 别名]
# 或者: from django_redis import get_redis_connection [as 别名]
def test_freeze_user_final_grade_error2(self, raise_on_exception, mock_refr, mock_get_fg):
"""
Test for freeze_user_final_grade function in case of problems with refresh of cache
"""
mock_refr.side_effect = AttributeError
if not raise_on_exception:
final_grade = api.freeze_user_final_grade(self.user, self.run_fa, raise_on_exception=raise_on_exception)
assert final_grade is None
else:
with self.assertRaises(FreezeGradeFailedException):
api.freeze_user_final_grade(self.user, self.run_fa, raise_on_exception=raise_on_exception)
assert mock_get_fg.called is False
mock_refr.assert_called_once_with(self.user)
assert FinalGrade.objects.filter(user=self.user, course_run=self.run_fa).exists() is False
con = get_redis_connection("redis")
failed_users_cache_key = api.CACHE_KEY_FAILED_USERS_BASE_STR.format(self.run_fa.edx_course_key)
failed_users_count = con.llen(failed_users_cache_key)
failed_users_list = list(map(int, con.lrange(failed_users_cache_key, 0, failed_users_count)))
assert self.user.id in failed_users_list
示例4: test_freeze_user_final_grade_error3
# 需要导入模块: import django_redis [as 别名]
# 或者: from django_redis import get_redis_connection [as 别名]
def test_freeze_user_final_grade_error3(self, raise_on_exception, mock_refr, mock_get_fg):
"""
Test for freeze_user_final_grade function in case of problems with getting the final grade
"""
mock_get_fg.side_effect = AttributeError
if not raise_on_exception:
final_grade = api.freeze_user_final_grade(self.user, self.run_fa, raise_on_exception=raise_on_exception)
assert final_grade is None
else:
with self.assertRaises(FreezeGradeFailedException):
api.freeze_user_final_grade(self.user, self.run_fa, raise_on_exception=raise_on_exception)
mock_refr.assert_called_once_with(self.user)
mock_get_fg.assert_called_once_with(self.user, self.run_fa)
assert FinalGrade.objects.filter(user=self.user, course_run=self.run_fa).exists() is False
con = get_redis_connection("redis")
failed_users_cache_key = api.CACHE_KEY_FAILED_USERS_BASE_STR.format(self.run_fa.edx_course_key)
failed_users_count = con.llen(failed_users_cache_key)
failed_users_list = list(map(int, con.lrange(failed_users_cache_key, 0, failed_users_count)))
assert self.user.id in failed_users_list
示例5: get_context_data
# 需要导入模块: import django_redis [as 别名]
# 或者: from django_redis import get_redis_connection [as 别名]
def get_context_data(self, **kwargs): # pylint: disable=arguments-differ
data = super(ServerList, self).get_context_data(**kwargs)
redis_server = get_redis_connection("judge")
sem = Semaphore(redis_server)
sem.exists_or_init()
try:
data['semaphore_available_count'] = sem.available_count
data['semaphore_available_keys'] = redis_server.lrange(sem.available_key, 0,
sem.available_count) # 1 more actually
data['semaphore_available_keys'] = list(map(lambda s: s.decode(), data['semaphore_available_keys']))
data['semaphore_grabbed_keys'] = {}
for key, tt in redis_server.hgetall(sem.grabbed_key).items():
data['semaphore_grabbed_keys'][key.decode()] = sem.current_time - float(tt.decode())
data['server_synchronize_status_detail'] = cache.get('server_synchronize_status_detail', '')
data['server_synchronize_status'] = cache.get('server_synchronize_status', 0)
data['semaphore_ok'] = True
except:
pass
data['crashed_submission_count'] = Submission.objects.filter(status=SubmissionStatus.SYSTEM_ERROR).count()
return data
示例6: setUpClass
# 需要导入模块: import django_redis [as 别名]
# 或者: from django_redis import get_redis_connection [as 别名]
def setUpClass(cls):
try:
from django_redis import get_redis_connection
cls.redis_connections = [get_redis_connection(connection_name) for connection_name in list(settings.CACHES.keys())]
except ImportError as exc:
raise ImportError("django_redis must be installed to use RedisTestCase. Exception details:- {0}".format(repr(exc)))
except AttributeError as exc:
raise AttributeError("settings file doesn't have redis configuration defined. Define CACHES in test settings file. Exception details:- {0}".format(repr(exc)))
super(RedisTestMixin, cls).setUpClass()
示例7: lock
# 需要导入模块: import django_redis [as 别名]
# 或者: from django_redis import get_redis_connection [as 别名]
def lock(cls, org, uuid):
return get_redis_connection().lock(GROUP_LOCK_KEY % (org.pk, uuid), timeout=60)
示例8: lock
# 需要导入模块: import django_redis [as 别名]
# 或者: from django_redis import get_redis_connection [as 别名]
def lock(cls, org, uuid):
return get_redis_connection().lock(LABEL_LOCK_KEY % (org.pk, uuid), timeout=60)
示例9: get_connection
# 需要导入模块: import django_redis [as 别名]
# 或者: from django_redis import get_redis_connection [as 别名]
def get_connection(list_key: str = Conf.PREFIX) -> Redis:
if django_redis and Conf.DJANGO_REDIS:
return django_redis.get_redis_connection(Conf.DJANGO_REDIS)
if isinstance(Conf.REDIS, str):
return redis.from_url(Conf.REDIS)
return redis.StrictRedis(**Conf.REDIS)
示例10: __init__
# 需要导入模块: import django_redis [as 别名]
# 或者: from django_redis import get_redis_connection [as 别名]
def __init__(self, name="default", topic="default", nrecents=1000,
expiration=86400, **kwargs):
super().__init__(**kwargs)
self.redis = get_redis_connection(name)
self.topic = topic
self.nrecents = nrecents
self.expiration = expiration
示例11: redis
# 需要导入模块: import django_redis [as 别名]
# 或者: from django_redis import get_redis_connection [as 别名]
def redis(self):
try:
return self._redis
except AttributeError:
self._redis = get_redis_connection("default")
return self._redis
示例12: check_redis_connected
# 需要导入模块: import django_redis [as 别名]
# 或者: from django_redis import get_redis_connection [as 别名]
def check_redis_connected(app_configs, **kwargs):
"""
A Django check to connect to the default redis connection
using ``django_redis.get_redis_connection`` and see if Redis
responds to a ``PING`` command.
"""
import redis
from django_redis import get_redis_connection
errors = []
try:
connection = get_redis_connection("default")
except redis.ConnectionError as e:
msg = "Could not connect to redis: {!s}".format(e)
errors.append(checks.Error(msg, id=health.ERROR_CANNOT_CONNECT_REDIS))
except NotImplementedError as e:
msg = "Redis client not available: {!s}".format(e)
errors.append(checks.Error(msg, id=health.ERROR_MISSING_REDIS_CLIENT))
except ImproperlyConfigured as e:
msg = 'Redis misconfigured: "{!s}"'.format(e)
errors.append(checks.Error(msg, id=health.ERROR_MISCONFIGURED_REDIS))
else:
result = connection.ping()
if not result:
msg = "Redis ping failed"
errors.append(checks.Error(msg, id=health.ERROR_REDIS_PING_FAILED))
return errors
示例13: handle
# 需要导入模块: import django_redis [as 别名]
# 或者: from django_redis import get_redis_connection [as 别名]
def handle(self, **options):
if (
not options["flush_stats"]
and not options["flush_rqdata"]
and not options["flush_django_cache"]
and not options["flush_all"]
):
raise CommandError(
"No options were provided. Use one of "
"--django-cache, --rqdata, --stats or --all."
)
self.stdout.write("Flushing cache...")
if options["flush_stats"] or options["flush_all"]:
# Delete all stats cache data.
r_con = get_redis_connection("stats")
r_con.flushdb()
self.stdout.write("All stats data removed.")
if options["flush_rqdata"] or options["flush_all"]:
# Flush all rq data, dirty counter and restore Pootle revision
# value.
r_con = get_redis_connection("redis")
r_con.flushdb()
self.stdout.write("RQ data removed.")
Revision.set(Unit.max_revision())
self.stdout.write("Max unit revision restored.")
if options["flush_django_cache"] or options["flush_all"]:
r_con = get_redis_connection("default")
r_con.flushdb()
self.stdout.write("All default Django cache data removed.")
示例14: _from_internal_network
# 需要导入模块: import django_redis [as 别名]
# 或者: from django_redis import get_redis_connection [as 别名]
def _from_internal_network(ip):
redis = get_redis_connection('default')
return redis.sismember('ip-whitelist', ip)
示例15: get_query_mask
# 需要导入模块: import django_redis [as 别名]
# 或者: from django_redis import get_redis_connection [as 别名]
def get_query_mask(query_hash: str) -> List[int]:
"""
Fetches an existing query mask for a given query hash
or returns an empty one.
:param query_hash: Unique value for a particular query.
:return: Boolean mask as a list of integers (0 or 1).
"""
redis = get_redis_connection("default")
key = f'{query_hash}:dead_link_mask'
return list(map(int, redis.lrange(key, 0, -1)))