├── tests ├── __init__.py ├── migrations │ ├── __init__.py │ └── 0001_initial.py ├── apps.py ├── models.py ├── fixtures │ └── albums.json └── tests.py ├── cache_extension ├── __init__.py ├── backends │ ├── __init__.py │ └── redis.py ├── cached_fields.py ├── utils.py ├── cache_keys.py └── cache.py ├── requirements.txt ├── CHANGELOG.md ├── .gitignore ├── .travis.yml ├── docs ├── index.rst ├── quick_start.rst ├── make.bat ├── Makefile └── conf.py ├── setup.py ├── runtests.py └── README.md /tests/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /cache_extension/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /tests/migrations/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /cache_extension/backends/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | django-redis==4.4.4 2 | redis==2.10.5 3 | hiredis==0.2.0 4 | -------------------------------------------------------------------------------- /tests/apps.py: -------------------------------------------------------------------------------- 1 | from django.apps import AppConfig 2 | 3 | 4 | class CacheTestConfig(AppConfig): 5 | name = 'cache_test' 6 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | ## 1.1.3 2 | 3 | * default client class is `django_redis.client.DefaultClient`, before is `cache_extension.backends.redis.ExtensionClient` 4 | 5 | * support `zremrangebyrank` command 6 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | __pycache__ 2 | *.pyc 3 | *.py~ 4 | build 5 | dist 6 | MANIFEST 7 | django_cache_extension.egg-info 8 | .DS_STORE 9 | db.sqlite3 10 | docs/_build 11 | docs/_static 12 | docs/_templates 13 | -------------------------------------------------------------------------------- /tests/models.py: -------------------------------------------------------------------------------- 1 | from django.db import models 2 | from cache_extension.utils import clear_model_cache 3 | 4 | 5 | # Create your models here. 6 | class Album(models.Model): 7 | artist = models.CharField(max_length=128) 8 | title = models.CharField(max_length=128) 9 | 10 | clear_model_cache(Album) 11 | clear_model_cache(Album, 'artist') 12 | clear_model_cache(Album, model_list_fields=['artist']) 13 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: python 2 | services: redis 3 | python: 4 | - "2.7" 5 | - "3.5" 6 | env: 7 | - DJANGO_VERSION=1.6 8 | - DJANGO_VERSION=1.7 9 | - DJANGO_VERSION=1.8 10 | - DJANGO_VERSION=1.9 11 | install: 12 | - pip install -q Django==$DJANGO_VERSION 13 | - pip install -r requirements.txt 14 | script: python runtests.py 15 | matrix: 16 | exclude: 17 | - python: "3.5" 18 | env: DJANGO_VERSION=1.6 19 | - python: "3.5" 20 | env: DJANGO_VERSION=1.7 21 | -------------------------------------------------------------------------------- /tests/fixtures/albums.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "pk": 1, 4 | "model": "tests.album", 5 | "fields": {"artist":"Taylor Swift", "title": "1989"} 6 | }, 7 | { 8 | "pk": 2, 9 | "model": "tests.album", 10 | "fields": {"artist":"Taylor Swift", "title": "Red"} 11 | }, 12 | { 13 | "pk": 3, 14 | "model": "tests.album", 15 | "fields": {"artist":"Taylor Swift", "title": "Fearless"} 16 | }, 17 | { 18 | "pk": 4, 19 | "model": "tests.album", 20 | "fields": {"artist":"Taylor Swift", "title": "Taylor Swift"} 21 | }, 22 | { 23 | "pk": 5, 24 | "model": "tests.album", 25 | "fields": {"artist":"Taylor Swift", "title": "Speak Now"} 26 | } 27 | ] 28 | -------------------------------------------------------------------------------- /tests/migrations/0001_initial.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Generated by Django 1.9.1 on 2016-04-22 02:36 3 | from __future__ import unicode_literals 4 | 5 | from django.db import migrations, models 6 | 7 | 8 | class Migration(migrations.Migration): 9 | 10 | initial = True 11 | 12 | dependencies = [ 13 | ] 14 | 15 | operations = [ 16 | migrations.CreateModel( 17 | name='Album', 18 | fields=[ 19 | ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), 20 | ('artist', models.CharField(max_length=128)), 21 | ('title', models.CharField(max_length=128)), 22 | ], 23 | ), 24 | ] 25 | -------------------------------------------------------------------------------- /docs/index.rst: -------------------------------------------------------------------------------- 1 | .. django cache extension documentation master file, created by 2 | sphinx-quickstart on Fri Apr 22 17:35:30 2016. 3 | You can adapt this file completely to your liking, but it should at least 4 | contain the root `toctree` directive. 5 | 6 | Welcome to django cache extension's documentation! 7 | ================================================== 8 | ``django cache extension`` is a extension package for cache use in django. 9 | ``django cache extension`` is now works with django 1.9 and python3. 10 | 11 | 12 | content 13 | ----------- 14 | 15 | .. toctree:: 16 | :maxdepth: 2 17 | 18 | quick_start 19 | 20 | 21 | 22 | Indices and tables 23 | ================== 24 | 25 | * :ref:`genindex` 26 | * :ref:`modindex` 27 | * :ref:`search` 28 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import setup 2 | 3 | setup( 4 | name='django-cache-extension', 5 | version='1.1.10', 6 | description='cache extension for django', 7 | url='https://github.com/Beeblio/django-cache-extension', 8 | author='Shanbay python dev group', 9 | author_email='developer@shanbay.com', 10 | license='MIT', 11 | classifiers=[ 12 | 'Development Status :: 3 - Alpha', 13 | 'Intended Audience :: Developers', 14 | 'Topic :: Software Development :: Build Tools', 15 | 'License :: OSI Approved :: MIT License', 16 | 'Programming Language :: Python :: 3', 17 | 'Programming Language :: Python :: 3.2', 18 | 'Programming Language :: Python :: 3.3', 19 | 'Programming Language :: Python :: 3.4', 20 | 'Programming Language :: Python :: 3.5', 21 | ], 22 | packages=['cache_extension'], 23 | package_data={'cache_extension': ['backends/*.py']}, 24 | install_requires=['django-redis', 'redis', 'hiredis'], 25 | ) 26 | -------------------------------------------------------------------------------- /cache_extension/cached_fields.py: -------------------------------------------------------------------------------- 1 | from django.db import models 2 | from django.core.cache import cache 3 | from django.utils.functional import curry 4 | 5 | 6 | class CachedModel(models.Model): 7 | 8 | def _cached_FIELD(self, field, cache_exc): 9 | value = getattr(self, field.attname) 10 | Model = field.related_model 11 | return cache.get_model(Model, pk=value, cache_exc=cache_exc) 12 | 13 | class Meta: 14 | abstract = True 15 | 16 | 17 | class ForeignKeyField(models.ForeignKey): 18 | 19 | def __init__(self, *args, **kwargs): 20 | self.cache_exc = kwargs.pop('cache_exc', False) 21 | super(ForeignKeyField, self).__init__(*args, **kwargs) 22 | 23 | def contribute_to_class(self, cls, name, **kwargs): 24 | super(models.ForeignKey, self).contribute_to_class(cls, name, **kwargs) 25 | if issubclass(cls, models.Model): 26 | setattr(cls, "cached_%s" % self.name, 27 | property(curry(CachedModel._cached_FIELD, field=self, 28 | cache_exc=self.cache_exc))) 29 | 30 | 31 | class OneToOneField(models.OneToOneField, ForeignKeyField): 32 | pass 33 | -------------------------------------------------------------------------------- /cache_extension/utils.py: -------------------------------------------------------------------------------- 1 | from django.core.cache import cache 2 | from django.db.models.signals import post_save, post_delete 3 | 4 | 5 | def apply_decorator(cls): 6 | def decorator(cls, func): 7 | def wrapper(*args, **kwargs): 8 | module_name = cls.__module__ 9 | if module_name.endswith('.cache_keys'): 10 | module_name = module_name.rsplit('.', 1)[0] 11 | 12 | function_name = func.__name__[len('key_of_'):] 13 | 14 | return '.'.join([module_name, function_name, 15 | str(func(*args, **kwargs) or '')]) 16 | return wrapper 17 | 18 | for key, value in cls.__dict__.items(): 19 | if key.startswith('key_of_'): 20 | setattr(cls, key, staticmethod(decorator(cls, value))) 21 | return cls 22 | 23 | 24 | def clear_model_cache(Model, *args, **cache_kwargs): 25 | def clear_model(sender, instance, **kwargs): 26 | cache.clear_model(instance) 27 | if args: 28 | cache.clear_model(instance, *args) 29 | 30 | fields = cache_kwargs.get('model_list_fields') 31 | if fields is not None: 32 | cache.clear_model_list(instance, *fields) 33 | 34 | post_save.connect(clear_model, sender=Model, weak=False) 35 | post_delete.connect(clear_model, sender=Model, weak=False) 36 | -------------------------------------------------------------------------------- /docs/quick_start.rst: -------------------------------------------------------------------------------- 1 | Quick Start 2 | =========== 3 | 4 | config 5 | ------- 6 | 1. Install ``cache extension`` by pip:: 7 | 8 | pip install django-cache-extension 9 | 10 | 2. For redis backend use cache like this:: 11 | 12 | config your cache file backend to cache_extension: 13 | 14 | CACHES={ 15 | "default": { 16 | 'BACKEND': 'cache_extension.backends.redis.ExtensionRedisBackend', 17 | 'LOCATION': 'redis://redis:6379/0', 18 | 'TIMEOUT': '172800', 19 | "KEY_PREFIX": "cache_extension", 20 | 'OPTIONS': { 21 | "DB": 0, 22 | "CLIENT_CLASS": "django_redis.client.DefaultClient", 23 | 'PARSER_CLASS': 'redis.connection.HiredisParser', 24 | 'PICKLE_VERSION': 2, 25 | } 26 | } 27 | }, 28 | 29 | 30 | methods 31 | ------- 32 | 33 | .. method:: get_model(model, pk=None, cache_exc=False, **kwargs) 34 | 35 | Return django model in cache, query database when cache miss hit, raise Model.DoesNotExist when miss database. 36 | 37 | Set cache_exc=True where cache model.DoesNotExist in cache, and return None. 38 | 39 | 40 | .. method:: get_model_list(model, **kwargs) 41 | 42 | Get multiple models with filter on fields, return a list of models. 43 | 44 | .. method:: clear_model(model, *args) 45 | 46 | clear model cache on args, usually use id. 47 | 48 | .. method:: clear_model_list(model, *agrs) 49 | 50 | Clear model cache using field name. 51 | 52 | .. method:: clear_model_cache(model, *agrs, **kwargs) 53 | 54 | Call clear_model or clear_model_list dynamically according to params passed. 55 | -------------------------------------------------------------------------------- /runtests.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import sys 3 | import os 4 | import warnings 5 | 6 | from django.conf import settings 7 | from django.core.management import execute_from_command_line 8 | 9 | 10 | # Build paths inside the project like this: os.path.join(BASE_DIR, ...) 11 | BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 12 | 13 | if not settings.configured: 14 | settings.configure( 15 | DATABASES={ 16 | 'default': { 17 | 'ENGINE': 'django.db.backends.sqlite3', 18 | } 19 | }, 20 | INSTALLED_APPS=[ 21 | 'cache_extension', 22 | 'tests', 23 | ], 24 | CACHES={ 25 | "default": { 26 | 'NAME': '17bdc', 27 | 'BACKEND': 'cache_extension.backends.redis.ExtensionRedisBackend', 28 | 'LOCATION': 'redis://localhost:6379/0', 29 | 'TIMEOUT': '172800', 30 | "KEY_PREFIX": "cache_extension", 31 | 'OPTIONS': { 32 | "DB": 0, 33 | 'PARSER_CLASS': 'redis.connection.HiredisParser', 34 | 'PICKLE_VERSION': 2, 35 | } 36 | }, 37 | "redis": { 38 | 'NAME': '17bdc', 39 | 'BACKEND': 'cache_extension.backends.redis.ExtensionRedisBackend', 40 | 'LOCATION': 'redis://localhost:6379/0', 41 | 'TIMEOUT': '172800', 42 | "KEY_PREFIX": "cache_extension", 43 | 'OPTIONS': { 44 | "DB": 0, 45 | "CLIENT_CLASS": "cache_extension.backends.redis.ExtensionClient", 46 | 'PARSER_CLASS': 'redis.connection.HiredisParser', 47 | 'PICKLE_VERSION': 2, 48 | } 49 | } 50 | }, 51 | 52 | MIDDLEWARE_CLASSES=[], 53 | ) 54 | 55 | 56 | warnings.simplefilter('default', DeprecationWarning) 57 | warnings.simplefilter('default', PendingDeprecationWarning) 58 | 59 | 60 | def runtests(): 61 | argv = sys.argv[:1] + ['test'] + sys.argv[1:] 62 | execute_from_command_line(argv) 63 | 64 | 65 | if __name__ == '__main__': 66 | runtests() 67 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ===== 2 | Django cache extension 3 | ===== 4 | 5 | [![Build Status](https://travis-ci.org/shanbay/django-cache-extension.svg?branch=master)](https://travis-ci.org/shanbay/django-cache-extension) 6 | 7 | Add extension methods to cache 8 | 9 | Quick start 10 | ----------- 11 | 12 | 1. Install ``cache extension`` by pip:: 13 | 14 | pip install django-cache-extension 15 | 16 | 2. For redis backend use cache like this:: 17 | 18 | config your cache file backend to cache_extension: 19 | 20 | ``` 21 | CACHES={ 22 | "default": { 23 | 'BACKEND': 'cache_extension.backends.redis.ExtensionRedisBackend', 24 | 'LOCATION': 'redis://redis:6379/0', 25 | 'TIMEOUT': '172800', 26 | "KEY_PREFIX": "cache_extension", 27 | 'OPTIONS': { 28 | "DB": 0, 29 | "CLIENT_CLASS": "django_redis.client.DefaultClient", 30 | 'PARSER_CLASS': 'redis.connection.HiredisParser', 31 | 'PICKLE_VERSION': 2, 32 | } 33 | } 34 | }, 35 | ``` 36 | 37 | 3. For custom cache backend:: 38 | 39 | ``` 40 | from cache_extension.cache import ExtensionCache 41 | from some_module import CustomCache 42 | class ExtensionCustomCache(ExtensionCache, CustomCache): 43 | pass 44 | ``` 45 | 46 | 47 | 4. Use extension cache methods:: 48 | 49 | ``` 50 | cache.get_model(Article, pk=1) 51 | cache.get_models(Article, [1,2,3]) 52 | cache.get_model(UserArticle, user_id=1, article_id=1) 53 | cache.get_model_list(UserArticle, user_id=1) 54 | ``` 55 | 56 | 5. Built in cached fields: ForeignKeyField, OneToOneField. 57 | 58 | Say you have two models defined as below: 59 | 60 | ``` 61 | from django.db import models 62 | from cache_extension import cached_fields 63 | 64 | 65 | class Foo(models.Model): 66 | pass 67 | 68 | class Bar(models.Model): 69 | foo = cached_fields.ForeignKeyField(Foo) 70 | 71 | ``` 72 | 73 | Then instances of Bar will have a `cached_foo` property which will try to fetch foo from cache first, if cache misses, will fallback to database. 74 | ``` 75 | bar = Bar.objects.get(pk=1) 76 | bar.cached_foo # cached foreign field, really handy 77 | ``` 78 | 79 | -------------------------------------------------------------------------------- /cache_extension/cache_keys.py: -------------------------------------------------------------------------------- 1 | from django.db.models import ForeignKey 2 | try: 3 | from django.core.exceptions import FieldDoesNotExist 4 | except: 5 | # for old django version 6 | from django.db.models.fields import FieldDoesNotExist 7 | 8 | def key_of_model(cls, *args, **kwargs): 9 | args, kwargs = transform_args(args, kwargs) 10 | if 'id' in kwargs: 11 | kwargs['pk'] = kwargs.pop('id') 12 | 13 | key_prefix = "%s.%s" % (cls.__module__, cls.__name__) 14 | if hasattr(cls, 'cache_version'): 15 | key_prefix += ".%s" % (getattr(cls, 'cache_version')) 16 | 17 | if args: 18 | if len(args) != 2: 19 | raise ValueError('args must be [field, val]') 20 | keys = "%s.%s" % (args[0], args[1]) 21 | else: 22 | valid, msg = validate_fields(cls, kwargs) 23 | if not valid: 24 | raise ValueError(msg) 25 | keys = sorted(["%s.%s" % item for item in kwargs.items()]) 26 | keys = '.'.join(keys) 27 | return "%s.%s" % (key_prefix, keys) 28 | 29 | 30 | def key_of_model_list(cls, **kwargs): 31 | args, kwargs = transform_args([], kwargs) 32 | valid, msg = validate_fields(cls, kwargs) 33 | if not valid: 34 | raise ValueError(msg) 35 | 36 | if 'id' in kwargs: 37 | kwargs['pk'] = kwargs.pop('id') 38 | 39 | key_prefix = "list.%s.%s" % (cls.__module__, cls.__name__) 40 | if hasattr(cls, 'list_cache_version'): 41 | key_prefix += ".%s" % (getattr(cls, 'list_cache_version')) 42 | 43 | # if len(kwargs) == 0 means i want get all 44 | if hasattr(cls, 'list_cache_version'): 45 | key_prefix += ".%s" % (getattr(cls, 'list_cache_version')) 46 | keys = sorted(["%s.%s" % item for item in kwargs.items()]) 47 | keys = '.'.join(keys) 48 | return "%s.%s" % (key_prefix, keys) 49 | 50 | 51 | def validate_fields(cls, fields): 52 | for key, value in fields.items(): 53 | if key in ['pk', 'id']: 54 | continue 55 | if not key.endswith('_id') and '__' not in key: 56 | field = cls._meta.get_field(key) 57 | if isinstance(field, ForeignKey): 58 | return False, 'must use FIELD_id on related fields' 59 | return True, 'SUCCESS' 60 | 61 | def transform_args(args, kwargs): 62 | new_args = [] 63 | for a in args: 64 | if isinstance(a, bytes): 65 | a = a.decode() 66 | new_args.append(a) 67 | for k,i in kwargs.items(): 68 | if isinstance(i, bytes): 69 | kwargs[k] = i.decode() 70 | 71 | return new_args, kwargs 72 | -------------------------------------------------------------------------------- /tests/tests.py: -------------------------------------------------------------------------------- 1 | from django import get_version 2 | from django.test import TestCase 3 | from django.core.cache import cache 4 | from cache_extension.backends.redis import SUPPORT_CMDS 5 | from cache_extension.utils import apply_decorator 6 | from cache_extension import cache_keys 7 | from .models import Album 8 | 9 | if get_version() >= '1.7': 10 | from django.core.cache import caches 11 | REDIS_CACHE = caches['redis'] 12 | else: 13 | from django.core.cache import get_cache 14 | REDIS_CACHE = get_cache('redis') 15 | 16 | 17 | class CacheTest(TestCase): 18 | fixtures = ['albums.json'] 19 | 20 | def setUp(self): 21 | all_albums = Album.objects.filter(artist="Taylor Swift") 22 | self.num_albums = all_albums.count() 23 | self.album_ids = all_albums.values_list('id', flat=True) 24 | 25 | def tearDown(self): 26 | Album.objects.all().delete() 27 | cache.clear() 28 | 29 | def test_cache(self): 30 | album = cache.get_model(Album, artist="Taylor Swift", 31 | title="Taylor Swift") 32 | self.assertEqual(album.artist, "Taylor Swift") 33 | 34 | try: 35 | album = cache.get_model(Album, artist="Tay-Tay") 36 | except Album.DoesNotExist: 37 | album = cache.get_model(Album, cache_exc=True, artist="Tay-Tay") 38 | 39 | self.assertEqual(album, None) 40 | 41 | Album(artist="Tay-Tay", title="1989").save() 42 | 43 | result_model = cache.get_model(Album, cache_exc=True, artist="Tay-Tay") 44 | self.assertEqual(result_model.artist, "Tay-Tay") 45 | 46 | albums = cache.get_model_list(Album, artist="Taylor Swift") 47 | self.assertEqual(len(albums), self.num_albums) 48 | 49 | albums = cache.get_models(Album, self.album_ids) 50 | self.assertEqual(len(albums), len(self.album_ids)) 51 | 52 | album = Album.objects.create(artist="Tay-Tay", title="Red") 53 | cache.set_model(album) 54 | result_album = cache.get_model(Album, pk=album.pk) 55 | self.assertEqual(album.pk, result_album.pk) 56 | 57 | cache.set_model_list(Album, artist="Tay-Tay") 58 | num_albums = Album.objects.filter(artist="Tay-Tay").count() 59 | albums_tay = cache.get_model_list(Album, artist="Tay-Tay") 60 | self.assertEqual(len(albums_tay), num_albums) 61 | cache.clear_models(Album, 'artist', ["Tay-Tay"]) 62 | 63 | def test_add_model_field(self): 64 | album = Album.objects.get(pk=1) 65 | result = { 66 | f.attname: getattr(album, f.attname) for f in album._meta.fields 67 | } 68 | result['another_field'] = '1' 69 | 70 | key = cache_keys.key_of_model(Album, pk=1) 71 | cache.set(key, result) 72 | key = cache_keys.key_of_model_list(Album, artist="Taylor Swift") 73 | cache.set(key, [result]) 74 | 75 | album = cache.get_model(Album, pk=1) 76 | self.assertRaises(AttributeError, lambda: album.another_field) 77 | 78 | def test_incr(self): 79 | key = "album_total_num" 80 | cache.set(key, self.num_albums) 81 | result = cache.incr(key, 1) 82 | self.assertEqual(result, self.num_albums+1) 83 | 84 | def test_other_cmd(self): 85 | key = "album_ids" 86 | ids = REDIS_CACHE.smembers(key) 87 | self.assertEqual(ids, set([])) 88 | 89 | for cmd in SUPPORT_CMDS: 90 | getattr(REDIS_CACHE, cmd) 91 | 92 | # test use cmd not in SUPPORT_CMDS list 93 | with self.assertRaises(KeyError): 94 | getattr(REDIS_CACHE, 'tests') 95 | 96 | # test 'StrictRedis' object has no attribute 'hstrlen' 97 | # test not support redis cmd 98 | SUPPORT_CMDS.append('hstrlen') 99 | with self.assertRaises(AttributeError): 100 | getattr(REDIS_CACHE, 'hstrlen') 101 | 102 | def test_cache_decorator(self): 103 | 104 | @apply_decorator 105 | class Cache_key: 106 | 107 | def key_of_test_cache_key(id): 108 | return '%s_v1' % id 109 | 110 | self.assertEqual(Cache_key.key_of_test_cache_key(1), 111 | 'tests.tests.test_cache_key.1_v1') 112 | 113 | def test_bytes_key(self): 114 | album_id = str(Album.objects.first().id).encode() 115 | album = cache.get_model(Album, id=album_id) 116 | self.assertEqual(album.artist, "Taylor Swift") 117 | -------------------------------------------------------------------------------- /cache_extension/backends/redis.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import 2 | from cache_extension.cache import ExtensionCache 3 | from django_redis.cache import RedisCache, omit_exception 4 | from django_redis.client.default import _main_exceptions, DefaultClient 5 | from django_redis.exceptions import ConnectionInterrupted 6 | from redis.client import StrictPipeline 7 | from redis.exceptions import ResponseError 8 | 9 | KEY_CMDS = [ 10 | 'exists', 'expire', 'expireat', 'rename', 'ttl', 'incrby', 'incrbyfloat', 11 | ] 12 | # not support hstrlen 13 | HASH_CMDS = [ 14 | 'hdel', 'hexists', 'hget', 'hgetall', 'hincrby', 'hincrbyfloat', 'hkeys', 15 | 'hlen', 'hmget', 'hmset', 'hset', 'hsetnx', 'hvals', 'hscan', 16 | ] 17 | # first arg must be key, so this cmds not support: brpoplpush, rpoplpush 18 | LIST_CMDS = [ 19 | 'blpop', 'brpop', 'lindex', 'linsert', 'llen', 20 | 'lpop', 'lpush', 'lpushx', 'lrange', 'lrem', 'lset', 21 | 'ltrim', 'rpop', 'rpush', 'rpushx', 22 | ] 23 | SET_CMDS = [ 24 | 'sadd', 'scard', 'sismember', 'smembers', 'spop', 'srem', 25 | 'srandmember', 'sinter', 'sinterstore', 'sdiff', 'sdiffstore', 26 | 'sunion', 'sunionstore', 27 | ] 28 | ZSET_CMDS = [ 29 | 'zadd', 'zcard', 'zcount', 'zincrby', 'zrange', 'zrem', 30 | 'zrevrange', 'zscore', 'zremrangebyrank' 31 | ] 32 | 33 | SUPPORT_CMDS = KEY_CMDS + HASH_CMDS + LIST_CMDS + SET_CMDS + ZSET_CMDS 34 | 35 | 36 | class ExtensionPipeline(StrictPipeline): 37 | def __init__(self, connection_pool, response_callbacks, transaction, 38 | shard_hint, make_key_func): 39 | super(ExtensionPipeline, self).__init__( 40 | connection_pool, 41 | response_callbacks, 42 | transaction, 43 | shard_hint 44 | ) 45 | 46 | self.make_key = make_key_func 47 | 48 | def pipeline_execute_command(self, *args, **options): 49 | args = list(args) 50 | key = args[1] 51 | args[1] = str(self.make_key(key)) 52 | # print("pipeline exec", args) 53 | # print("pipeline exec opt", options) 54 | 55 | return super( 56 | ExtensionPipeline, self 57 | ).pipeline_execute_command(*args, **options) 58 | 59 | 60 | class ExtensionClient(DefaultClient): 61 | 62 | def pipeline(self, transaction=True, shard_hint=None): 63 | client = self.get_client() 64 | 65 | return ExtensionPipeline( 66 | client.connection_pool, 67 | client.response_callbacks, 68 | transaction, 69 | shard_hint, 70 | self.make_key) 71 | 72 | def __getattr__(self, cmd): 73 | client = self.get_client() 74 | return getattr(client, cmd) 75 | 76 | 77 | class ExtensionRedisBackend(ExtensionCache, RedisCache): 78 | 79 | def __init__(self, server, params): 80 | options = params.get("OPTIONS", {}) 81 | default_client = "django_redis.client.DefaultClient" 82 | client_class = options.get('CLIENT_CLASS', default_client) 83 | options['CLIENT_CLASS'] = client_class 84 | params['options'] = options 85 | super(ExtensionRedisBackend, self).__init__(server, params) 86 | 87 | @omit_exception 88 | def incr(self, key, delta=1, version=None, client=None): 89 | 90 | if not client: 91 | client = self.client.get_client(write=True) 92 | 93 | key = self.make_key(key, version=version) 94 | 95 | try: 96 | try: 97 | value = client.incr(key, delta) 98 | except ResponseError: 99 | # if cached value or total value is greater than 64 bit signed 100 | # integer. 101 | # elif int is encoded. so redis sees the data as string. 102 | # In this situations redis will throw ResponseError 103 | 104 | # try to keep TTL of key 105 | timeout = client.ttl(key) 106 | value = self.get(key, version=version, client=client) + delta 107 | self.set(key, value, version=version, timeout=timeout, 108 | client=client) 109 | except _main_exceptions as e: 110 | raise ConnectionInterrupted(connection=client, parent=e) 111 | 112 | return value 113 | 114 | def pipeline(self, transaction=True, shard_hint=None): 115 | return self.client.pipeline(transaction=transaction, 116 | shard_hint=shard_hint) 117 | 118 | def __getattr__(self, cmd): 119 | if cmd not in SUPPORT_CMDS: 120 | raise KeyError("not supported redis commands") 121 | 122 | func = getattr(self.client, cmd) 123 | 124 | def redis_cmd(key, *args, **kwargs): 125 | key = self.make_key(key) 126 | if cmd == 'rename': 127 | dest = args[0] 128 | dest = self.make_key(dest) 129 | args = list(args) 130 | args[0] = dest 131 | 132 | # print("exec", cmd, key, args, kwargs) 133 | return func(key, *args, **kwargs) 134 | 135 | return redis_cmd 136 | -------------------------------------------------------------------------------- /cache_extension/cache.py: -------------------------------------------------------------------------------- 1 | from django.db import IntegrityError 2 | from functools import partial 3 | from cache_extension import cache_keys 4 | 5 | 6 | class ModelNotExist(object): 7 | pass 8 | 9 | 10 | class ExtensionCache(object): 11 | 12 | def get_attrs(self, model): 13 | return { 14 | f.attname: getattr(model, f.attname) for f in model._meta.fields} 15 | 16 | def get_or_create_model(self, cls, *args, **kwargs): 17 | try: 18 | model = self.get_model(cls, *args, **kwargs) 19 | return model, False 20 | except cls.DoesNotExist: 21 | if args: 22 | if len(args) > 1: 23 | raise ValueError('multi field should pass by kwargs') 24 | kwargs = {'pk': args[0]} 25 | try: 26 | model = cls.objects.create(**kwargs) 27 | except IntegrityError: 28 | model = cls.objects.get(**kwargs) 29 | 30 | return model, True 31 | 32 | def get_model(self, cls, cache_exc=False, **kwargs): 33 | key = cache_keys.key_of_model(cls, **kwargs) 34 | attrs = self.get(key) 35 | if not attrs: 36 | try: 37 | model = cls.objects.get(**kwargs) 38 | self.set(key, self.get_attrs(model)) 39 | except cls.DoesNotExist: 40 | if not cache_exc: 41 | raise cls.DoesNotExist 42 | model = None 43 | self.set(key, ModelNotExist()) 44 | elif isinstance(attrs, ModelNotExist): 45 | if not cache_exc: 46 | raise cls.DoesNotExist 47 | model = None 48 | else: 49 | fields = set([field.attname for field in cls._meta.fields]) 50 | attrs_keys = set(attrs.keys()) 51 | diff = attrs_keys - fields 52 | for key in diff: 53 | attrs.pop(key) 54 | model = cls(**attrs) 55 | return model 56 | 57 | def set_model(self, instance, *args): 58 | if instance is None: 59 | raise ValueError("can not cache a none model") 60 | key = self._make_model_key(instance, *args) 61 | attrs = self.get_attrs(instance) 62 | self.set(key, attrs) 63 | 64 | def clear_model(self, instance, *args): 65 | key = self._make_model_key(instance, *args) 66 | self.delete(key) 67 | 68 | def clear_models(self, instance, field, vals): 69 | keys = [cache_keys.key_of_model( 70 | instance, **{field: val}) for val in vals] 71 | self.delete_many(keys) 72 | 73 | def get_many_by_vals(self, vals, key_func): 74 | keys = [key_func(val) for val in vals] 75 | ret = self.get_many(keys) 76 | if ret: 77 | _ = {} 78 | m = dict(zip(keys, vals)) 79 | for k, v in ret.items(): 80 | _[m[k]] = v 81 | ret = _ 82 | return ret 83 | 84 | def get_models(self, cls, vals, field='pk', version=None, sort=False): 85 | ''' get multiple models in multiple keys 86 | ''' 87 | key_func = partial(cache_keys.key_of_model, cls, field) 88 | models = self.get_many_by_vals(vals, key_func=key_func) 89 | fields = set([f.attname for f in cls._meta.fields]) 90 | for model in models.values(): 91 | attrs_keys = set(model.keys()) 92 | diff = attrs_keys - fields 93 | for key in diff: 94 | model.pop(key) 95 | 96 | exists_models = [cls(**m) for m in models.values()] 97 | if len(exists_models) == len(vals): 98 | models = exists_models 99 | else: 100 | miss_vals = set(vals) - set(models.keys()) 101 | kwargs = {'%s__in' % field: miss_vals} 102 | miss_models = list(cls.objects.filter(**kwargs)) 103 | data = { 104 | key_func(getattr(m, field)): self.get_attrs(m) 105 | for m in miss_models 106 | } 107 | self.set_many(data) 108 | models = exists_models + miss_models 109 | if sort: 110 | models = sorted( 111 | models, key=lambda m: vals.index(getattr(m, field))) 112 | return models 113 | 114 | def get_model_list(self, cls, **kwargs): 115 | ''' get multiple models in one key 116 | ''' 117 | key = cache_keys.key_of_model_list(cls, **kwargs) 118 | models = self.get(key) 119 | if models: 120 | fields = set([f.attname for f in cls._meta.fields]) 121 | for model in models: 122 | attrs_keys = set(model.keys()) 123 | diff = attrs_keys - fields 124 | for key in diff: 125 | model.pop(key) 126 | return [cls(**model) for model in models] 127 | models = list(cls.objects.filter(**kwargs)) 128 | data = [self.get_attrs(m) for m in models] 129 | self.set(key, data) 130 | return models 131 | 132 | def set_model_list(self, cls, models=None, **kwargs): 133 | key = cache_keys.key_of_model_list(cls, **kwargs) 134 | if models is None: 135 | models = list(cls.objects.filter(**kwargs)) 136 | data = [self.get_attrs(m) for m in models] 137 | self.set(key, data) 138 | 139 | def clear_model_list(self, instance, *args): 140 | key = self._make_model_list_key(instance, *args) 141 | self.delete(key) 142 | 143 | def _make_model_key(self, instance, *args): 144 | args = args or ['pk'] 145 | kwargs = dict([(field, getattr(instance, field)) for field in args]) 146 | return cache_keys.key_of_model(instance.__class__, **kwargs) 147 | 148 | def _make_model_list_key(self, instance, *args): 149 | kwargs = dict([(field, getattr(instance, field)) for field in args]) 150 | key = cache_keys.key_of_model_list(instance.__class__, **kwargs) 151 | return key 152 | 153 | def fetch(self, key, block): 154 | data = self.get(key) 155 | if data is None: 156 | data = block() 157 | self.set(key, data) 158 | return data 159 | -------------------------------------------------------------------------------- /docs/make.bat: -------------------------------------------------------------------------------- 1 | @ECHO OFF 2 | 3 | REM Command file for Sphinx documentation 4 | 5 | if "%SPHINXBUILD%" == "" ( 6 | set SPHINXBUILD=sphinx-build 7 | ) 8 | set BUILDDIR=_build 9 | set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% . 10 | set I18NSPHINXOPTS=%SPHINXOPTS% . 11 | if NOT "%PAPER%" == "" ( 12 | set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% 13 | set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS% 14 | ) 15 | 16 | if "%1" == "" goto help 17 | 18 | if "%1" == "help" ( 19 | :help 20 | echo.Please use `make ^` where ^ is one of 21 | echo. html to make standalone HTML files 22 | echo. dirhtml to make HTML files named index.html in directories 23 | echo. singlehtml to make a single large HTML file 24 | echo. pickle to make pickle files 25 | echo. json to make JSON files 26 | echo. htmlhelp to make HTML files and a HTML help project 27 | echo. qthelp to make HTML files and a qthelp project 28 | echo. devhelp to make HTML files and a Devhelp project 29 | echo. epub to make an epub 30 | echo. epub3 to make an epub3 31 | echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter 32 | echo. text to make text files 33 | echo. man to make manual pages 34 | echo. texinfo to make Texinfo files 35 | echo. gettext to make PO message catalogs 36 | echo. changes to make an overview over all changed/added/deprecated items 37 | echo. xml to make Docutils-native XML files 38 | echo. pseudoxml to make pseudoxml-XML files for display purposes 39 | echo. linkcheck to check all external links for integrity 40 | echo. doctest to run all doctests embedded in the documentation if enabled 41 | echo. coverage to run coverage check of the documentation if enabled 42 | echo. dummy to check syntax errors of document sources 43 | goto end 44 | ) 45 | 46 | if "%1" == "clean" ( 47 | for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i 48 | del /q /s %BUILDDIR%\* 49 | goto end 50 | ) 51 | 52 | 53 | REM Check if sphinx-build is available and fallback to Python version if any 54 | %SPHINXBUILD% 1>NUL 2>NUL 55 | if errorlevel 9009 goto sphinx_python 56 | goto sphinx_ok 57 | 58 | :sphinx_python 59 | 60 | set SPHINXBUILD=python -m sphinx.__init__ 61 | %SPHINXBUILD% 2> nul 62 | if errorlevel 9009 ( 63 | echo. 64 | echo.The 'sphinx-build' command was not found. Make sure you have Sphinx 65 | echo.installed, then set the SPHINXBUILD environment variable to point 66 | echo.to the full path of the 'sphinx-build' executable. Alternatively you 67 | echo.may add the Sphinx directory to PATH. 68 | echo. 69 | echo.If you don't have Sphinx installed, grab it from 70 | echo.http://sphinx-doc.org/ 71 | exit /b 1 72 | ) 73 | 74 | :sphinx_ok 75 | 76 | 77 | if "%1" == "html" ( 78 | %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html 79 | if errorlevel 1 exit /b 1 80 | echo. 81 | echo.Build finished. The HTML pages are in %BUILDDIR%/html. 82 | goto end 83 | ) 84 | 85 | if "%1" == "dirhtml" ( 86 | %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml 87 | if errorlevel 1 exit /b 1 88 | echo. 89 | echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. 90 | goto end 91 | ) 92 | 93 | if "%1" == "singlehtml" ( 94 | %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml 95 | if errorlevel 1 exit /b 1 96 | echo. 97 | echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. 98 | goto end 99 | ) 100 | 101 | if "%1" == "pickle" ( 102 | %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle 103 | if errorlevel 1 exit /b 1 104 | echo. 105 | echo.Build finished; now you can process the pickle files. 106 | goto end 107 | ) 108 | 109 | if "%1" == "json" ( 110 | %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json 111 | if errorlevel 1 exit /b 1 112 | echo. 113 | echo.Build finished; now you can process the JSON files. 114 | goto end 115 | ) 116 | 117 | if "%1" == "htmlhelp" ( 118 | %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp 119 | if errorlevel 1 exit /b 1 120 | echo. 121 | echo.Build finished; now you can run HTML Help Workshop with the ^ 122 | .hhp project file in %BUILDDIR%/htmlhelp. 123 | goto end 124 | ) 125 | 126 | if "%1" == "qthelp" ( 127 | %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp 128 | if errorlevel 1 exit /b 1 129 | echo. 130 | echo.Build finished; now you can run "qcollectiongenerator" with the ^ 131 | .qhcp project file in %BUILDDIR%/qthelp, like this: 132 | echo.^> qcollectiongenerator %BUILDDIR%\qthelp\djangocacheextension.qhcp 133 | echo.To view the help file: 134 | echo.^> assistant -collectionFile %BUILDDIR%\qthelp\djangocacheextension.ghc 135 | goto end 136 | ) 137 | 138 | if "%1" == "devhelp" ( 139 | %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp 140 | if errorlevel 1 exit /b 1 141 | echo. 142 | echo.Build finished. 143 | goto end 144 | ) 145 | 146 | if "%1" == "epub" ( 147 | %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub 148 | if errorlevel 1 exit /b 1 149 | echo. 150 | echo.Build finished. The epub file is in %BUILDDIR%/epub. 151 | goto end 152 | ) 153 | 154 | if "%1" == "epub3" ( 155 | %SPHINXBUILD% -b epub3 %ALLSPHINXOPTS% %BUILDDIR%/epub3 156 | if errorlevel 1 exit /b 1 157 | echo. 158 | echo.Build finished. The epub3 file is in %BUILDDIR%/epub3. 159 | goto end 160 | ) 161 | 162 | if "%1" == "latex" ( 163 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 164 | if errorlevel 1 exit /b 1 165 | echo. 166 | echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. 167 | goto end 168 | ) 169 | 170 | if "%1" == "latexpdf" ( 171 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 172 | cd %BUILDDIR%/latex 173 | make all-pdf 174 | cd %~dp0 175 | echo. 176 | echo.Build finished; the PDF files are in %BUILDDIR%/latex. 177 | goto end 178 | ) 179 | 180 | if "%1" == "latexpdfja" ( 181 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 182 | cd %BUILDDIR%/latex 183 | make all-pdf-ja 184 | cd %~dp0 185 | echo. 186 | echo.Build finished; the PDF files are in %BUILDDIR%/latex. 187 | goto end 188 | ) 189 | 190 | if "%1" == "text" ( 191 | %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text 192 | if errorlevel 1 exit /b 1 193 | echo. 194 | echo.Build finished. The text files are in %BUILDDIR%/text. 195 | goto end 196 | ) 197 | 198 | if "%1" == "man" ( 199 | %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man 200 | if errorlevel 1 exit /b 1 201 | echo. 202 | echo.Build finished. The manual pages are in %BUILDDIR%/man. 203 | goto end 204 | ) 205 | 206 | if "%1" == "texinfo" ( 207 | %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo 208 | if errorlevel 1 exit /b 1 209 | echo. 210 | echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo. 211 | goto end 212 | ) 213 | 214 | if "%1" == "gettext" ( 215 | %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale 216 | if errorlevel 1 exit /b 1 217 | echo. 218 | echo.Build finished. The message catalogs are in %BUILDDIR%/locale. 219 | goto end 220 | ) 221 | 222 | if "%1" == "changes" ( 223 | %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes 224 | if errorlevel 1 exit /b 1 225 | echo. 226 | echo.The overview file is in %BUILDDIR%/changes. 227 | goto end 228 | ) 229 | 230 | if "%1" == "linkcheck" ( 231 | %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck 232 | if errorlevel 1 exit /b 1 233 | echo. 234 | echo.Link check complete; look for any errors in the above output ^ 235 | or in %BUILDDIR%/linkcheck/output.txt. 236 | goto end 237 | ) 238 | 239 | if "%1" == "doctest" ( 240 | %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest 241 | if errorlevel 1 exit /b 1 242 | echo. 243 | echo.Testing of doctests in the sources finished, look at the ^ 244 | results in %BUILDDIR%/doctest/output.txt. 245 | goto end 246 | ) 247 | 248 | if "%1" == "coverage" ( 249 | %SPHINXBUILD% -b coverage %ALLSPHINXOPTS% %BUILDDIR%/coverage 250 | if errorlevel 1 exit /b 1 251 | echo. 252 | echo.Testing of coverage in the sources finished, look at the ^ 253 | results in %BUILDDIR%/coverage/python.txt. 254 | goto end 255 | ) 256 | 257 | if "%1" == "xml" ( 258 | %SPHINXBUILD% -b xml %ALLSPHINXOPTS% %BUILDDIR%/xml 259 | if errorlevel 1 exit /b 1 260 | echo. 261 | echo.Build finished. The XML files are in %BUILDDIR%/xml. 262 | goto end 263 | ) 264 | 265 | if "%1" == "pseudoxml" ( 266 | %SPHINXBUILD% -b pseudoxml %ALLSPHINXOPTS% %BUILDDIR%/pseudoxml 267 | if errorlevel 1 exit /b 1 268 | echo. 269 | echo.Build finished. The pseudo-XML files are in %BUILDDIR%/pseudoxml. 270 | goto end 271 | ) 272 | 273 | if "%1" == "dummy" ( 274 | %SPHINXBUILD% -b dummy %ALLSPHINXOPTS% %BUILDDIR%/dummy 275 | if errorlevel 1 exit /b 1 276 | echo. 277 | echo.Build finished. Dummy builder generates no files. 278 | goto end 279 | ) 280 | 281 | :end 282 | -------------------------------------------------------------------------------- /docs/Makefile: -------------------------------------------------------------------------------- 1 | # Makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line. 5 | SPHINXOPTS = 6 | SPHINXBUILD = sphinx-build 7 | PAPER = 8 | BUILDDIR = _build 9 | 10 | # User-friendly check for sphinx-build 11 | ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1) 12 | $(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don\'t have Sphinx installed, grab it from http://sphinx-doc.org/) 13 | endif 14 | 15 | # Internal variables. 16 | PAPEROPT_a4 = -D latex_paper_size=a4 17 | PAPEROPT_letter = -D latex_paper_size=letter 18 | ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 19 | # the i18n builder cannot share the environment and doctrees with the others 20 | I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 21 | 22 | .PHONY: help 23 | help: 24 | @echo "Please use \`make ' where is one of" 25 | @echo " html to make standalone HTML files" 26 | @echo " dirhtml to make HTML files named index.html in directories" 27 | @echo " singlehtml to make a single large HTML file" 28 | @echo " pickle to make pickle files" 29 | @echo " json to make JSON files" 30 | @echo " htmlhelp to make HTML files and a HTML help project" 31 | @echo " qthelp to make HTML files and a qthelp project" 32 | @echo " applehelp to make an Apple Help Book" 33 | @echo " devhelp to make HTML files and a Devhelp project" 34 | @echo " epub to make an epub" 35 | @echo " epub3 to make an epub3" 36 | @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" 37 | @echo " latexpdf to make LaTeX files and run them through pdflatex" 38 | @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" 39 | @echo " text to make text files" 40 | @echo " man to make manual pages" 41 | @echo " texinfo to make Texinfo files" 42 | @echo " info to make Texinfo files and run them through makeinfo" 43 | @echo " gettext to make PO message catalogs" 44 | @echo " changes to make an overview of all changed/added/deprecated items" 45 | @echo " xml to make Docutils-native XML files" 46 | @echo " pseudoxml to make pseudoxml-XML files for display purposes" 47 | @echo " linkcheck to check all external links for integrity" 48 | @echo " doctest to run all doctests embedded in the documentation (if enabled)" 49 | @echo " coverage to run coverage check of the documentation (if enabled)" 50 | @echo " dummy to check syntax errors of document sources" 51 | 52 | .PHONY: clean 53 | clean: 54 | rm -rf $(BUILDDIR)/* 55 | 56 | .PHONY: html 57 | html: 58 | $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html 59 | @echo 60 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." 61 | 62 | .PHONY: dirhtml 63 | dirhtml: 64 | $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml 65 | @echo 66 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." 67 | 68 | .PHONY: singlehtml 69 | singlehtml: 70 | $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml 71 | @echo 72 | @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." 73 | 74 | .PHONY: pickle 75 | pickle: 76 | $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle 77 | @echo 78 | @echo "Build finished; now you can process the pickle files." 79 | 80 | .PHONY: json 81 | json: 82 | $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json 83 | @echo 84 | @echo "Build finished; now you can process the JSON files." 85 | 86 | .PHONY: htmlhelp 87 | htmlhelp: 88 | $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp 89 | @echo 90 | @echo "Build finished; now you can run HTML Help Workshop with the" \ 91 | ".hhp project file in $(BUILDDIR)/htmlhelp." 92 | 93 | .PHONY: qthelp 94 | qthelp: 95 | $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp 96 | @echo 97 | @echo "Build finished; now you can run "qcollectiongenerator" with the" \ 98 | ".qhcp project file in $(BUILDDIR)/qthelp, like this:" 99 | @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/djangocacheextension.qhcp" 100 | @echo "To view the help file:" 101 | @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/djangocacheextension.qhc" 102 | 103 | .PHONY: applehelp 104 | applehelp: 105 | $(SPHINXBUILD) -b applehelp $(ALLSPHINXOPTS) $(BUILDDIR)/applehelp 106 | @echo 107 | @echo "Build finished. The help book is in $(BUILDDIR)/applehelp." 108 | @echo "N.B. You won't be able to view it unless you put it in" \ 109 | "~/Library/Documentation/Help or install it in your application" \ 110 | "bundle." 111 | 112 | .PHONY: devhelp 113 | devhelp: 114 | $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp 115 | @echo 116 | @echo "Build finished." 117 | @echo "To view the help file:" 118 | @echo "# mkdir -p $$HOME/.local/share/devhelp/djangocacheextension" 119 | @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/djangocacheextension" 120 | @echo "# devhelp" 121 | 122 | .PHONY: epub 123 | epub: 124 | $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub 125 | @echo 126 | @echo "Build finished. The epub file is in $(BUILDDIR)/epub." 127 | 128 | .PHONY: epub3 129 | epub3: 130 | $(SPHINXBUILD) -b epub3 $(ALLSPHINXOPTS) $(BUILDDIR)/epub3 131 | @echo 132 | @echo "Build finished. The epub3 file is in $(BUILDDIR)/epub3." 133 | 134 | .PHONY: latex 135 | latex: 136 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 137 | @echo 138 | @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." 139 | @echo "Run \`make' in that directory to run these through (pdf)latex" \ 140 | "(use \`make latexpdf' here to do that automatically)." 141 | 142 | .PHONY: latexpdf 143 | latexpdf: 144 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 145 | @echo "Running LaTeX files through pdflatex..." 146 | $(MAKE) -C $(BUILDDIR)/latex all-pdf 147 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 148 | 149 | .PHONY: latexpdfja 150 | latexpdfja: 151 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 152 | @echo "Running LaTeX files through platex and dvipdfmx..." 153 | $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja 154 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 155 | 156 | .PHONY: text 157 | text: 158 | $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text 159 | @echo 160 | @echo "Build finished. The text files are in $(BUILDDIR)/text." 161 | 162 | .PHONY: man 163 | man: 164 | $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man 165 | @echo 166 | @echo "Build finished. The manual pages are in $(BUILDDIR)/man." 167 | 168 | .PHONY: texinfo 169 | texinfo: 170 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 171 | @echo 172 | @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." 173 | @echo "Run \`make' in that directory to run these through makeinfo" \ 174 | "(use \`make info' here to do that automatically)." 175 | 176 | .PHONY: info 177 | info: 178 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 179 | @echo "Running Texinfo files through makeinfo..." 180 | make -C $(BUILDDIR)/texinfo info 181 | @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." 182 | 183 | .PHONY: gettext 184 | gettext: 185 | $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale 186 | @echo 187 | @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." 188 | 189 | .PHONY: changes 190 | changes: 191 | $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes 192 | @echo 193 | @echo "The overview file is in $(BUILDDIR)/changes." 194 | 195 | .PHONY: linkcheck 196 | linkcheck: 197 | $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck 198 | @echo 199 | @echo "Link check complete; look for any errors in the above output " \ 200 | "or in $(BUILDDIR)/linkcheck/output.txt." 201 | 202 | .PHONY: doctest 203 | doctest: 204 | $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest 205 | @echo "Testing of doctests in the sources finished, look at the " \ 206 | "results in $(BUILDDIR)/doctest/output.txt." 207 | 208 | .PHONY: coverage 209 | coverage: 210 | $(SPHINXBUILD) -b coverage $(ALLSPHINXOPTS) $(BUILDDIR)/coverage 211 | @echo "Testing of coverage in the sources finished, look at the " \ 212 | "results in $(BUILDDIR)/coverage/python.txt." 213 | 214 | .PHONY: xml 215 | xml: 216 | $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml 217 | @echo 218 | @echo "Build finished. The XML files are in $(BUILDDIR)/xml." 219 | 220 | .PHONY: pseudoxml 221 | pseudoxml: 222 | $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml 223 | @echo 224 | @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." 225 | 226 | .PHONY: dummy 227 | dummy: 228 | $(SPHINXBUILD) -b dummy $(ALLSPHINXOPTS) $(BUILDDIR)/dummy 229 | @echo 230 | @echo "Build finished. Dummy builder generates no files." 231 | -------------------------------------------------------------------------------- /docs/conf.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | # 4 | # django cache extension documentation build configuration file, created by 5 | # sphinx-quickstart on Fri Apr 22 17:35:30 2016. 6 | # 7 | # This file is execfile()d with the current directory set to its 8 | # containing dir. 9 | # 10 | # Note that not all possible configuration values are present in this 11 | # autogenerated file. 12 | # 13 | # All configuration values have a default; values that are commented out 14 | # serve to show the default. 15 | 16 | import sys 17 | import os 18 | 19 | # If extensions (or modules to document with autodoc) are in another directory, 20 | # add these directories to sys.path here. If the directory is relative to the 21 | # documentation root, use os.path.abspath to make it absolute, like shown here. 22 | #sys.path.insert(0, os.path.abspath('.')) 23 | 24 | # -- General configuration ------------------------------------------------ 25 | 26 | # If your documentation needs a minimal Sphinx version, state it here. 27 | #needs_sphinx = '1.0' 28 | 29 | # Add any Sphinx extension module names here, as strings. They can be 30 | # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom 31 | # ones. 32 | extensions = [] 33 | 34 | # Add any paths that contain templates here, relative to this directory. 35 | templates_path = ['_templates'] 36 | 37 | # The suffix(es) of source filenames. 38 | # You can specify multiple suffix as a list of string: 39 | # source_suffix = ['.rst', '.md'] 40 | source_suffix = '.rst' 41 | 42 | # The encoding of source files. 43 | #source_encoding = 'utf-8-sig' 44 | 45 | # The master toctree document. 46 | master_doc = 'index' 47 | 48 | # General information about the project. 49 | project = 'django cache extension' 50 | copyright = '2016, damao lee' 51 | author = 'damao lee' 52 | 53 | # The version info for the project you're documenting, acts as replacement for 54 | # |version| and |release|, also used in various other places throughout the 55 | # built documents. 56 | # 57 | # The short X.Y version. 58 | version = '1.0.0' 59 | # The full version, including alpha/beta/rc tags. 60 | release = '1.0.0' 61 | 62 | # The language for content autogenerated by Sphinx. Refer to documentation 63 | # for a list of supported languages. 64 | # 65 | # This is also used if you do content translation via gettext catalogs. 66 | # Usually you set "language" from the command line for these cases. 67 | language = None 68 | 69 | # There are two options for replacing |today|: either, you set today to some 70 | # non-false value, then it is used: 71 | #today = '' 72 | # Else, today_fmt is used as the format for a strftime call. 73 | #today_fmt = '%B %d, %Y' 74 | 75 | # List of patterns, relative to source directory, that match files and 76 | # directories to ignore when looking for source files. 77 | # This patterns also effect to html_static_path and html_extra_path 78 | exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] 79 | 80 | # The reST default role (used for this markup: `text`) to use for all 81 | # documents. 82 | #default_role = None 83 | 84 | # If true, '()' will be appended to :func: etc. cross-reference text. 85 | #add_function_parentheses = True 86 | 87 | # If true, the current module name will be prepended to all description 88 | # unit titles (such as .. function::). 89 | #add_module_names = True 90 | 91 | # If true, sectionauthor and moduleauthor directives will be shown in the 92 | # output. They are ignored by default. 93 | #show_authors = False 94 | 95 | # The name of the Pygments (syntax highlighting) style to use. 96 | pygments_style = 'sphinx' 97 | 98 | # A list of ignored prefixes for module index sorting. 99 | #modindex_common_prefix = [] 100 | 101 | # If true, keep warnings as "system message" paragraphs in the built documents. 102 | #keep_warnings = False 103 | 104 | # If true, `todo` and `todoList` produce output, else they produce nothing. 105 | todo_include_todos = False 106 | 107 | 108 | # -- Options for HTML output ---------------------------------------------- 109 | 110 | # The theme to use for HTML and HTML Help pages. See the documentation for 111 | # a list of builtin themes. 112 | # html_theme = 'alabaster' 113 | html_theme = 'default' 114 | 115 | 116 | # Theme options are theme-specific and customize the look and feel of a theme 117 | # further. For a list of options available for each theme, see the 118 | # documentation. 119 | #html_theme_options = {} 120 | 121 | # Add any paths that contain custom themes here, relative to this directory. 122 | #html_theme_path = [] 123 | 124 | # The name for this set of Sphinx documents. 125 | # " v documentation" by default. 126 | #html_title = 'django cache extension v1.0.0' 127 | 128 | # A shorter title for the navigation bar. Default is the same as html_title. 129 | #html_short_title = None 130 | 131 | # The name of an image file (relative to this directory) to place at the top 132 | # of the sidebar. 133 | #html_logo = None 134 | 135 | # The name of an image file (relative to this directory) to use as a favicon of 136 | # the docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 137 | # pixels large. 138 | #html_favicon = None 139 | 140 | # Add any paths that contain custom static files (such as style sheets) here, 141 | # relative to this directory. They are copied after the builtin static files, 142 | # so a file named "default.css" will overwrite the builtin "default.css". 143 | html_static_path = ['_static'] 144 | 145 | # Add any extra paths that contain custom files (such as robots.txt or 146 | # .htaccess) here, relative to this directory. These files are copied 147 | # directly to the root of the documentation. 148 | #html_extra_path = [] 149 | 150 | # If not None, a 'Last updated on:' timestamp is inserted at every page 151 | # bottom, using the given strftime format. 152 | # The empty string is equivalent to '%b %d, %Y'. 153 | #html_last_updated_fmt = None 154 | 155 | # If true, SmartyPants will be used to convert quotes and dashes to 156 | # typographically correct entities. 157 | #html_use_smartypants = True 158 | 159 | # Custom sidebar templates, maps document names to template names. 160 | #html_sidebars = {} 161 | 162 | # Additional templates that should be rendered to pages, maps page names to 163 | # template names. 164 | #html_additional_pages = {} 165 | 166 | # If false, no module index is generated. 167 | #html_domain_indices = True 168 | 169 | # If false, no index is generated. 170 | #html_use_index = True 171 | 172 | # If true, the index is split into individual pages for each letter. 173 | #html_split_index = False 174 | 175 | # If true, links to the reST sources are added to the pages. 176 | #html_show_sourcelink = True 177 | 178 | # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. 179 | #html_show_sphinx = True 180 | 181 | # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. 182 | #html_show_copyright = True 183 | 184 | # If true, an OpenSearch description file will be output, and all pages will 185 | # contain a tag referring to it. The value of this option must be the 186 | # base URL from which the finished HTML is served. 187 | #html_use_opensearch = '' 188 | 189 | # This is the file name suffix for HTML files (e.g. ".xhtml"). 190 | #html_file_suffix = None 191 | 192 | # Language to be used for generating the HTML full-text search index. 193 | # Sphinx supports the following languages: 194 | # 'da', 'de', 'en', 'es', 'fi', 'fr', 'h', 'it', 'ja' 195 | # 'nl', 'no', 'pt', 'ro', 'r', 'sv', 'tr', 'zh' 196 | #html_search_language = 'en' 197 | 198 | # A dictionary with options for the search language support, empty by default. 199 | # 'ja' uses this config value. 200 | # 'zh' user can custom change `jieba` dictionary path. 201 | #html_search_options = {'type': 'default'} 202 | 203 | # The name of a javascript file (relative to the configuration directory) that 204 | # implements a search results scorer. If empty, the default will be used. 205 | #html_search_scorer = 'scorer.js' 206 | 207 | # Output file base name for HTML help builder. 208 | htmlhelp_basename = 'djangocacheextensiondoc' 209 | 210 | # -- Options for LaTeX output --------------------------------------------- 211 | 212 | latex_elements = { 213 | # The paper size ('letterpaper' or 'a4paper'). 214 | #'papersize': 'letterpaper', 215 | 216 | # The font size ('10pt', '11pt' or '12pt'). 217 | #'pointsize': '10pt', 218 | 219 | # Additional stuff for the LaTeX preamble. 220 | #'preamble': '', 221 | 222 | # Latex figure (float) alignment 223 | #'figure_align': 'htbp', 224 | } 225 | 226 | # Grouping the document tree into LaTeX files. List of tuples 227 | # (source start file, target name, title, 228 | # author, documentclass [howto, manual, or own class]). 229 | latex_documents = [ 230 | (master_doc, 'djangocacheextension.tex', 'django cache extension Documentation', 231 | 'damao lee', 'manual'), 232 | ] 233 | 234 | # The name of an image file (relative to this directory) to place at the top of 235 | # the title page. 236 | #latex_logo = None 237 | 238 | # For "manual" documents, if this is true, then toplevel headings are parts, 239 | # not chapters. 240 | #latex_use_parts = False 241 | 242 | # If true, show page references after internal links. 243 | #latex_show_pagerefs = False 244 | 245 | # If true, show URL addresses after external links. 246 | #latex_show_urls = False 247 | 248 | # Documents to append as an appendix to all manuals. 249 | #latex_appendices = [] 250 | 251 | # If false, no module index is generated. 252 | #latex_domain_indices = True 253 | 254 | 255 | # -- Options for manual page output --------------------------------------- 256 | 257 | # One entry per manual page. List of tuples 258 | # (source start file, name, description, authors, manual section). 259 | man_pages = [ 260 | (master_doc, 'djangocacheextension', 'django cache extension Documentation', 261 | [author], 1) 262 | ] 263 | 264 | # If true, show URL addresses after external links. 265 | #man_show_urls = False 266 | 267 | 268 | # -- Options for Texinfo output ------------------------------------------- 269 | 270 | # Grouping the document tree into Texinfo files. List of tuples 271 | # (source start file, target name, title, author, 272 | # dir menu entry, description, category) 273 | texinfo_documents = [ 274 | (master_doc, 'djangocacheextension', 'django cache extension Documentation', 275 | author, 'djangocacheextension', 'One line description of project.', 276 | 'Miscellaneous'), 277 | ] 278 | 279 | # Documents to append as an appendix to all manuals. 280 | #texinfo_appendices = [] 281 | 282 | # If false, no module index is generated. 283 | #texinfo_domain_indices = True 284 | 285 | # How to display URL addresses: 'footnote', 'no', or 'inline'. 286 | #texinfo_show_urls = 'footnote' 287 | 288 | # If true, do not generate a @detailmenu in the "Top" node's menu. 289 | #texinfo_no_detailmenu = False 290 | --------------------------------------------------------------------------------