python - 在 django 请求之间共享单个连接

标签 python django redis connection-pooling

寻找一种在 django 项目中共享连接对象的可靠方式,类似于 django 数据库连接。

from django.db import connections
with connections['default'].cursor() as cursor:
    cursor.execute(sql, params)

不一定使用相同的 API,但我需要一种类似的方式来获取在 Django 服务器启动时初始化的 Redis 连接池,这样我就可以重用项目不同部分的单个连接池。

您对我如何解决这个问题有什么建议或想法吗?

最佳答案

在 django 中找到了对我有用的解决方案 CacheHandler

在本例中用于建立 REDIS 连接 redis-sentinel-url被使用。

settings.py - Redis 连接字符串定义在

REDIS = {
    "default": "redis:///",
    "secondary": "redis+sentinel:///"
}

RedisPoolHandler类实现类似django CacheHandler

from threading import local

import redis_sentinel_url
from django.conf import settings
from django.core.cache import InvalidCacheBackendError


class RedisClientHandler:
    """
    A Redis Client Handler to manage access to Redis instances.
    Ensure only one instance of each alias exists per thread.
    """
    def __init__(self):
        self._clients = local()

    def __getitem__(self, alias):
        try:
            return self._redis_clients.caches[alias]
        except AttributeError:
            self._redis_clients.caches = {}
        except KeyError:
            pass

        if alias not in settings.REDIS:
            raise InvalidCacheBackendError(
                "Could not find config for '%s' in settings.REDIS" % alias
            )

        value = settings.REDIS[alias]
        sentinel, redis_pool = redis_sentinel_url.connect(value, client_options={"decode_responses": True})

        self._redis_clients.caches[alias] = redis_pool
        return redis_pool

    def all(self):
        return getattr(self._redis_clients, '_redis_clients', {}).values()


redis_clients = RedisPoolHandler()

使用示例如下:

from path.to.classfile import redis_clients

redis_client = redis_clients['default']

关于python - 在 django 请求之间共享单个连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55496803/

相关文章:

python - celery 最好的方式管理/获取任务的eta

python - 如何将 csv 转换并格式化为列表列表,其中标题名称包含在值中

python - 添加随机加权点

django - “RelatedManager”对象在 DRF 序列化器中没有属性 'pk'

django - Django: “load”(在模板文件中)做什么?

python - APScheduler 作业未按计划启动

python - 在 tkinter 文件对话框中指定文件路径

python - 创建每月的 pandas DatetimeIndex

codeigniter - 如何扩展 Code igniter 缓存类 Redis 类

php - Redis 的 allkeys-lru maxmemory 策略是否要求 key 设置过期?