当前位置: 首页>>代码示例>>Python>>正文


Python django_redis.get_redis_connection方法代码示例

本文整理汇总了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 
开发者ID:rapidpro,项目名称:casepro,代码行数:27,代码来源:test_db.py

示例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)) 
开发者ID:creativecommons,项目名称:cccatalog-api,代码行数:24,代码来源:scheduled_tasks.py

示例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 
开发者ID:mitodl,项目名称:micromasters,代码行数:22,代码来源:api_test.py

示例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 
开发者ID:mitodl,项目名称:micromasters,代码行数:22,代码来源:api_test.py

示例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 
开发者ID:F0RE1GNERS,项目名称:eoj3,代码行数:23,代码来源:views.py

示例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() 
开发者ID:hspandher,项目名称:django-test-addons,代码行数:12,代码来源:mixins.py

示例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) 
开发者ID:rapidpro,项目名称:casepro,代码行数:4,代码来源:models.py

示例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) 
开发者ID:rapidpro,项目名称:casepro,代码行数:4,代码来源:models.py

示例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) 
开发者ID:Koed00,项目名称:django-q,代码行数:8,代码来源:redis_broker.py

示例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 
开发者ID:codeforboston,项目名称:cornerwise,代码行数:9,代码来源:logger.py

示例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 
开发者ID:webkom,项目名称:lego,代码行数:8,代码来源:storage.py

示例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 
开发者ID:mozilla-services,项目名称:python-dockerflow,代码行数:30,代码来源:checks.py

示例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.") 
开发者ID:evernote,项目名称:zing,代码行数:35,代码来源:flush_cache.py

示例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) 
开发者ID:creativecommons,项目名称:cccatalog-api,代码行数:5,代码来源:throttle.py

示例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))) 
开发者ID:creativecommons,项目名称:cccatalog-api,代码行数:13,代码来源:dead_link_mask.py


注:本文中的django_redis.get_redis_connection方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。