django-cacheops-用于ORM缓存的python库,具有自动粒度事件驱动失效功能
django-cacheops是用于ORM缓存的python库,具有自动粒度事件驱动失效功能。
它使用redis作为ORM缓存的后端,并将redis或文件系统用于简单的时间无效的后端。
特点
django-cacheops还有更多的特点:
装饰器以查询集或时间的形式缓存任何用户功能或视图
django和jinja2模板的扩展
透明的交易支持
狗堆预防机制
使django更快
安装
使用pip安装:pip install django-cacheops或者直接下载django-cacheops的源代码包。
用法
自动缓存
它是自动的,您只需要进行设置即可。
手动缓存
您可以通过调用任何查询集的.cache()方法来强制其使用缓存:
在这里,您可以指定应为查询集缓存哪些操作,例如,以下代码:
将缓存计数调用,Paginator但不缓存以后的文章提取。有五个可能的行动- ,get,,和。您可以将此操作的任何子集传递给方法,甚至是空方法,以关闭缓存。但是,后者有一个捷径:fetchcountaggregateexists.cache()
当您要禁用特定查询集上的自动缓存时,此功能很有用。
您还可以使用覆盖特定查询集的默认超时.cache(timeout=...)。
设定
添加cacheops到您的中INSTALLED_APPS。
设置redis连接并为所需模型启用缓存:
CACHEOPS_REDIS = { 'host': 'localhost', # redis-server is on same machine 'port': 6379, # default redis port 'db': 1, # SELECT non-default redis database # using separate redis db or redis instance # is highly recommended 'socket_timeout': 3, # connection timeout in seconds, optional 'password': '...', # optional 'unix_socket_path': '' # replaces host and port}# Alternatively the redis connection can be defined using a URL:CACHEOPS_REDIS = "redis://localhost:6379/1"# orCACHEOPS_REDIS = "unix://path/to/socket?db=1"# or with password (note a colon)CACHEOPS_REDIS = "redis://:password@localhost:6379/1"# If you want to use sentinel, specify this variableCACHEOPS_SENTINEL = { 'locations': [('localhost', 26379)], # sentinel locations, required 'service_name': 'mymaster', # sentinel service name, required 'socket_timeout': 0.1, # connection timeout in seconds, optional 'db': 0 # redis database, default: 0 ... # everything else is passed to Sentinel()}# To use your own redis client class,# should be compatible or subclass cacheops.redis.CacheopsRedisCACHEOPS_CLIENT_CLASS = 'your.redis.ClientClass'CACHEOPS = { # Automatically cache any User.objects.get() calls for 15 minutes # This also includes .first() and .last() calls, # as well as request.user or post.author access, # where Post.author is a foreign key to auth.User 'auth.user': {'ops': 'get', 'timeout': 60*15}, # Automatically cache all gets and queryset fetches # to other django.contrib.auth models for an hour 'auth.*': {'ops': {'fetch', 'get'}, 'timeout': 60*60}, # Cache all queries to Permission # 'all' is an alias for {'get', 'fetch', 'count', 'aggregate', 'exists'} 'auth.permission': {'ops': 'all', 'timeout': 60*60}, # Enable manual caching on all other models with default timeout of an hour # Use Post.objects.cache().get(...) # or Tags.objects.filter(...).order_by(...).cache() # to cache particular ORM request. # Invalidation is still automatic '*.*': {'ops': (), 'timeout': 60*60}, # And since ops is empty by default you can rewrite last line as: '*.*': {'timeout': 60*60}, # NOTE: binding signals has its overhead, like preventing fast mass deletes, # you might want to only register whatever you cache and dependencies. # Finally you can explicitely forbid even manual caching with: 'some_app.*': None,}
赞 (0)