Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -26,15 +26,15 @@ jobs:
strategy:
fail-fast: false
matrix:
python-version: ["3.8", "3.9", "3.10", "3.11", "3.12", "3.13", "pypy3.10"]
python-version: ["3.8", "3.9", "3.10", "3.11", "3.12", "3.13", "3.14", "pypy3.10"]
experimental: [false]
include:
- python-version: "3.13"
experimental: true

services:
postgres:
image: postgres
image: ${{ matrix.experimental && 'postgres:16' || 'postgres:15' }}
env:
POSTGRES_PASSWORD: cacheops
POSTGRES_USER: cacheops
Expand All @@ -46,7 +46,7 @@ jobs:
ports:
- 6379:6379
mysql:
image: mysql
image: mysql:8.4
env:
MYSQL_ROOT_PASSWORD: cacheops
MYSQL_DATABASE: cacheops
Expand Down
5 changes: 5 additions & 0 deletions CHANGELOG
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
Unreleased
- support and test against Python 3.14 and Django 6.0/6.1
- preserve Django 6.1 template tag argument validation and fetch mode behavior
- avoid fetching unchanged deferred one-to-one fields during partial saves

7.2
- support and test against Python 3.13 and Django 5.1/5.2 (thx to Stu Tomlinson)
- updated md5 to set usedforsecurity for FIPS compliance (Logan Bibby)
Expand Down
11 changes: 11 additions & 0 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ Requirements

Python 3.8+, Django 3.2+ and Redis 4.0+.

Django 6.0 and 6.1 are supported with Python 3.12, 3.13, and 3.14.


Installation
++++++++++++
Expand Down Expand Up @@ -785,6 +787,15 @@ more interest or a champion willing to implement it emerges.

All unsupported things could still be used easily enough with the help of ``@cached_as()``.

On Django 6.1, querysets using ``FETCH_PEERS``, ``FETCH_RAISE``, or custom fetch modes
bypass queryset caching, including ``local_get``. Instances using these modes are
also excluded from ``cache_on_save``. The default ``FETCH_ONE`` mode caches normally.

Django 6.1's database-level ``DB_CASCADE``, ``DB_SET_NULL``, and ``DB_SET_DEFAULT``
options do not emit model signals for related rows changed by the database.
Invalidate affected models explicitly with ``invalidate_model()`` after these
deletions, including dependencies of any ``@cached_as()`` functions.


Performance tips
----------------
Expand Down
31 changes: 22 additions & 9 deletions cacheops/query.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,10 @@
from .transaction import transaction_states
from .signals import cache_read


__all__ = ('cached_as', 'cached_view_as', 'install_cacheops')

_local_get_cache = {}
_FETCH_ONE = getattr(models, "FETCH_ONE", None)


def cached_as(*samples, timeout=None, extra=None, lock=None, keep_fresh=False):
Expand Down Expand Up @@ -181,10 +181,14 @@ def _cache_results(self, cache_key, results):

def _should_cache(self, op):
# If cache and op are enabled and not within write or dirty transaction
return settings.CACHEOPS_ENABLED \
and self._cacheprofile and op in self._cacheprofile['ops'] \
and not self._for_write \
return (
settings.CACHEOPS_ENABLED
and self._cacheprofile
and op in self._cacheprofile["ops"]
and getattr(self, "_fetch_mode", _FETCH_ONE) is _FETCH_ONE
and not self._for_write
and not transaction_states[self.db].is_dirty()
)

def cache(self, ops=None, timeout=None, lock=None):
"""
Expand Down Expand Up @@ -432,17 +436,20 @@ def _pre_save(self, sender, instance, using, **kwargs):
pass

@skip_on_no_invalidation
def _post_save(self, sender, instance, using, **kwargs):
def _post_save(self, sender, instance, using, update_fields=None, **kwargs):
# Invoke invalidations for both old and new versions of saved object
old = _old_objs.__dict__.pop((sender, instance.pk), None)
if old:
invalidate_obj(old, using=using)
invalidate_obj(instance, using=using)

invalidate_o2o(sender, old, instance, using=using)
invalidate_o2o(sender, old, instance, using=using, update_fields=update_fields)

# We run invalidations but skip caching if we are dirty
if transaction_states[using].is_dirty():
# Nondefault fetch modes cannot survive a cache round trip.
if (
transaction_states[using].is_dirty()
or getattr(instance._state, "fetch_mode", _FETCH_ONE) is not _FETCH_ONE
):
return

# NOTE: it's possible for this to be a subclass, e.g. proxy, without cacheprofile,
Expand Down Expand Up @@ -505,10 +512,16 @@ def invalidated_update(self, **kwargs):
return self.get_queryset().inplace().invalidated_update(**kwargs)


def invalidate_o2o(sender, old, instance, using=DEFAULT_DB_ALIAS):
def invalidate_o2o(sender, old, instance, using=DEFAULT_DB_ALIAS, update_fields=None):
"""Invoke invalidation for o2o reverse queries"""
o2o_fields = [f for f in sender._meta.fields if isinstance(f, models.OneToOneField)]
for f in o2o_fields:
if (
update_fields is not None
and f.name not in update_fields
and f.attname not in update_fields
):
continue
old_value = getattr(old, f.attname, None)
value = getattr(instance, f.attname)
if old_value != value:
Expand Down
27 changes: 22 additions & 5 deletions cacheops/templatetags/cacheops.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
from inspect import getfullargspec, unwrap
from functools import partial
from inspect import getfullargspec, unwrap

from django.template import Library
import django
from django.template import Library, TemplateSyntaxError
from django.template.library import TagHelperNode, parse_bits

import cacheops
from cacheops.utils import carefully_strip_whitespace


__all__ = ['CacheopsLibrary', 'invalidate_fragment']


Expand All @@ -26,9 +26,26 @@ def _compile(parser, token):

# args
bits = token.split_contents()[1:]
parse_params = params
if takes_context:
if not params or params[0] != "context":
raise TemplateSyntaxError(
f"'{name}' is decorated with takes_context=True so it must "
"have a first argument of 'context'"
)
parse_params = params[1:]
parse_kwargs = {"takes_context": False} if django.VERSION < (6, 1) else {}
args, kwargs = parse_bits(
parser, bits, params, varargs, varkw, defaults,
kwonly, kwonly_defaults, takes_context, name,
parser,
bits,
parse_params,
varargs,
varkw,
defaults,
kwonly,
kwonly_defaults,
name=name,
**parse_kwargs,
)
return CachedNode(func, takes_context, args, kwargs, nodelist)

Expand Down
3 changes: 3 additions & 0 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@
'Programming Language :: Python :: 3.11',
'Programming Language :: Python :: 3.12',
'Programming Language :: Python :: 3.13',
'Programming Language :: Python :: 3.14',
'Framework :: Django',
'Framework :: Django :: 3.2',
'Framework :: Django :: 4.0',
Expand All @@ -47,6 +48,8 @@
'Framework :: Django :: 5.0',
'Framework :: Django :: 5.1',
'Framework :: Django :: 5.2',
'Framework :: Django :: 6.0',
'Framework :: Django :: 6.1',

'Environment :: Web Environment',
'Intended Audience :: Developers',
Expand Down
2 changes: 2 additions & 0 deletions tests/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
'django.contrib.auth',
'tests',
]
if os.environ.get("CACHEOPS_DB") in {"postgresql", "postgis"}:
INSTALLED_APPS.append("django.contrib.postgres")

ROOT_URLCONF = 'tests.urls'

Expand Down
108 changes: 108 additions & 0 deletions tests/test_fetch_modes.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
import unittest

import django
from django.db import models

from cacheops import cached_as
from cacheops.query import _local_get_cache

from .models import CacheOnSaveModel, Category, Extra, Local, Post
from .utils import BaseTestCase, make_inc


@unittest.skipUnless(django.VERSION >= (6, 1), "Fetch modes require Django 6.1")
class FetchModeTests(BaseTestCase):
fixtures = ["basic"]

def setUp(self):
super().setUp()
_local_get_cache.clear()
self.addCleanup(_local_get_cache.clear)

def test_default_mode_still_caches(self):
with self.assertNumQueries(1):
Category.objects.cache().get(pk=1)
category = Category.objects.fetch_mode(models.FETCH_ONE).cache().get(pk=1)
self.assertEqual(category.title, "Django")

def test_raise_mode_does_not_reuse_default_cache(self):
from django.core.exceptions import FieldFetchBlocked

Category.objects.only("pk").cache().get(pk=1)
with self.assertNumQueries(1):
category = (
Category.objects.only("pk")
.fetch_mode(models.FETCH_RAISE)
.cache()
.get(pk=1)
)
with self.assertRaises(FieldFetchBlocked):
category.title

def test_default_mode_does_not_reuse_raise_cache(self):
Category.objects.only("pk").fetch_mode(models.FETCH_RAISE).cache().get(pk=1)
with self.assertNumQueries(1):
category = Category.objects.only("pk").cache().get(pk=1)
with self.assertNumQueries(1):
self.assertEqual(category.title, "Django")

def test_peer_mode_keeps_batching(self):
for _ in range(2):
with self.assertNumQueries(1):
qs = Category.objects.only("pk").fetch_mode(models.FETCH_PEERS).cache()
categories = list(qs)
with self.assertNumQueries(1):
titles = [category.title for category in categories]
self.assertCountEqual(
titles, ["Django", "Rails", "Perl", "Python", "Node.js"]
)

def test_local_get_does_not_mix_modes(self):
local = Local.objects.create(tag=42)
for mode in (models.FETCH_ONE, models.FETCH_RAISE, models.FETCH_PEERS):
with self.subTest(mode=mode):
with self.assertNumQueries(1):
fetched = Local.objects.fetch_mode(mode).cache().get(pk=local.pk)
self.assertIs(fetched._state.fetch_mode, mode)
with self.assertNumQueries(0):
fetched = Local.objects.cache().get(pk=local.pk)
self.assertIs(fetched._state.fetch_mode, models.FETCH_ONE)

def test_cache_on_save_does_not_store_nondefault_mode(self):
obj = CacheOnSaveModel.objects.create(title="old")
obj = (
CacheOnSaveModel.objects.fetch_mode(models.FETCH_RAISE)
.cache()
.get(pk=obj.pk)
)
obj.title = "new"
obj.save(update_fields=["title"])

with self.assertNumQueries(1):
fetched = CacheOnSaveModel.objects.cache().get(pk=obj.pk)
self.assertEqual(fetched.title, "new")
self.assertIs(fetched._state.fetch_mode, models.FETCH_ONE)

def test_save_does_not_fetch_unchanged_one_to_one(self):
extra = Extra.objects.only("pk", "tag").fetch_mode(models.FETCH_RAISE).get(pk=1)
extra.save(update_fields=["tag"])
self.assertNotIn("post_id", extra.__dict__)

def test_changed_one_to_one_still_invalidates(self):
for field in ("post", "post_id"):
with self.subTest(field=field):
extra = Extra.objects.get(pk=1)
old_post_id = extra.post_id
new_post_id = 3 if old_post_id == 1 else 1
old_calls = make_inc(
cached_as(Post.objects.filter(pk=old_post_id), extra=field)
)
new_calls = make_inc(
cached_as(Post.objects.filter(pk=new_post_id), extra=field)
)
self.assertEqual(old_calls(), 1)
self.assertEqual(new_calls(), 1)
extra.post_id = new_post_id
extra.save(update_fields=[field])
self.assertEqual(old_calls(), 2)
self.assertEqual(new_calls(), 2)
35 changes: 32 additions & 3 deletions tests/tests.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from contextlib import contextmanager
from functools import reduce
import operator
import pickle
import re
import platform
import unittest
Expand All @@ -11,7 +12,7 @@
from django.db import DEFAULT_DB_ALIAS
from django.test import override_settings
from django.test.client import RequestFactory
from django.template import Context, Template
from django.template import Context, Template, TemplateSyntaxError
from django.db.models import F, Count, Max, OuterRef, Sum, Subquery, Exists, Q
from django.db.models.expressions import RawSQL

Expand Down Expand Up @@ -178,7 +179,7 @@ def test_invalidated_update(self):
list(Post.objects.filter(category=2).cache())

def test_subquery(self):
categories = Category.objects.cache().filter(title='Django').only('id')
categories = Category.objects.cache().filter(title='Django').values('pk')
Post.objects.cache().filter(category__in=Subquery(categories)).count()

def test_rawsql(self):
Expand Down Expand Up @@ -435,6 +436,34 @@ def my_cached(context):
self.assertRendersTo(t, {'inc': inc, 'flag': True}, '.1.1')
self.assertRendersTo(t, {'inc': inc, 'flag': False}, '.2.3')

def test_decorator_tag_context_arguments(self):
@decorator_tag(takes_context=True)
def context_cached(context, timeout, *, fragment):
return cached(timeout=timeout, extra=(fragment, context['variant']))

inc = make_inc()
for _ in range(2):
t = Template("""
{% load cacheops %}
{% context_cached 60 fragment='context' %}.{{ inc }}{% endcontext_cached %}
{% context_cached timeout=60 fragment='context' %}.{{ inc }}{% endcontext_cached %}
""")
self.assertRendersTo(t, {'inc': inc, 'variant': 1}, '.1.1')

def test_decorator_tag_invalid_context(self):
def missing_context():
pass

def wrong_context(other):
pass

for func in (missing_context, wrong_context):
decorator_tag(takes_context=True)(func)
source = '{%% load cacheops %%}{%% %s %%}{%% end%s %%}' % (func.__name__, func.__name__)
with self.subTest(func=func.__name__):
with self.assertRaisesRegex(TemplateSyntaxError, "first argument of 'context'"):
Template(source)

def test_jinja2(self):
from jinja2 import Environment
env = Environment(extensions=['cacheops.jinja2.cache'])
Expand Down Expand Up @@ -659,7 +688,7 @@ def test_366(self):
def test_385(self):
Client.objects.create(name='Client Name')

with self.assertRaisesRegex(AttributeError, "local object"):
with self.assertRaisesRegex((AttributeError, pickle.PicklingError), "local object"):
Client.objects.filter(name='Client Name').cache().first()

invalidate_model(Client)
Expand Down
Loading
Loading