plain.cache 0.0.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,61 @@
1
+ ## Plain is released under the BSD 3-Clause License
2
+
3
+ BSD 3-Clause License
4
+
5
+ Copyright (c) 2023, Dropseed, LLC
6
+
7
+ Redistribution and use in source and binary forms, with or without
8
+ modification, are permitted provided that the following conditions are met:
9
+
10
+ 1. Redistributions of source code must retain the above copyright notice, this
11
+ list of conditions and the following disclaimer.
12
+
13
+ 2. Redistributions in binary form must reproduce the above copyright notice,
14
+ this list of conditions and the following disclaimer in the documentation
15
+ and/or other materials provided with the distribution.
16
+
17
+ 3. Neither the name of the copyright holder nor the names of its
18
+ contributors may be used to endorse or promote products derived from
19
+ this software without specific prior written permission.
20
+
21
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
22
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
24
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
25
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
27
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
28
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
29
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
30
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31
+
32
+
33
+ ## This package contains code forked from github.com/django/django
34
+
35
+ Copyright (c) Django Software Foundation and individual contributors.
36
+ All rights reserved.
37
+
38
+ Redistribution and use in source and binary forms, with or without modification,
39
+ are permitted provided that the following conditions are met:
40
+
41
+ 1. Redistributions of source code must retain the above copyright notice,
42
+ this list of conditions and the following disclaimer.
43
+
44
+ 2. Redistributions in binary form must reproduce the above copyright
45
+ notice, this list of conditions and the following disclaimer in the
46
+ documentation and/or other materials provided with the distribution.
47
+
48
+ 3. Neither the name of Django nor the names of its contributors may be used
49
+ to endorse or promote products derived from this software without
50
+ specific prior written permission.
51
+
52
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
53
+ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
54
+ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
55
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
56
+ ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
57
+ (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
58
+ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
59
+ ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
60
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
61
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
@@ -0,0 +1,10 @@
1
+ Metadata-Version: 2.1
2
+ Name: plain.cache
3
+ Version: 0.0.0
4
+ Summary:
5
+ Author: Dave Gaeddert
6
+ Author-email: dave.gaeddert@dropseed.dev
7
+ Requires-Python: >=3.11,<4.0
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: Programming Language :: Python :: 3.11
10
+ Classifier: Programming Language :: Python :: 3.12
@@ -0,0 +1,46 @@
1
+ # Cache
2
+
3
+ A simple cache using the database.
4
+
5
+ The Plain Cache stores JSON-serializable values in a `CachedItem` model.
6
+ Cached data can be set to expire after a certain amount of time.
7
+
8
+ Access to the cache is provided through the `Cached` class.
9
+
10
+ ```python
11
+ from plain.cache import Cached
12
+
13
+
14
+ cached = Cached("my-cache-key")
15
+
16
+ if cached.exists():
17
+ print("Cache hit and not expired!")
18
+ print(cached.value)
19
+ else:
20
+ print("Cache miss!")
21
+ cached.set("a JSON-serializable value", expiration=60)
22
+
23
+ # Delete the item if you need to
24
+ cached.delete()
25
+ ```
26
+
27
+ Expired cache items can be cleared with `plain cache clear-expired`.
28
+ You can run this on a schedule through various cron-like tools or [plain-worker](../../../plain-worker/plain/worker/).
29
+
30
+ ## Installation
31
+
32
+ Add `plain.cache` to your `INSTALLED_PACKAGES`:
33
+
34
+ ```python
35
+ # app/settings.py
36
+ INSTALLED_PACKAGES = [
37
+ # ...
38
+ "plain.cache",
39
+ ]
40
+ ```
41
+
42
+ ## CLI
43
+
44
+ - `plain cache clear-expired` - Clear all expired cache items
45
+ - `plain cache clear-all` - Clear all cache items
46
+ - `plain cache stats` - Show cache statistics
@@ -0,0 +1,5 @@
1
+ from .core import Cached
2
+
3
+ __all__ = [
4
+ "Cached",
5
+ ]
@@ -0,0 +1,32 @@
1
+ from plain.cache.models import CachedItem
2
+ from plain.staff.admin.views import (
3
+ AdminModelDetailView,
4
+ AdminModelListView,
5
+ AdminModelViewset,
6
+ register_viewset,
7
+ )
8
+
9
+
10
+ @register_viewset
11
+ class CachedItemViewset(AdminModelViewset):
12
+ class ListView(AdminModelListView):
13
+ nav_section = "Cache"
14
+ model = CachedItem
15
+ title = "Cached items"
16
+ fields = [
17
+ "key",
18
+ "created_at",
19
+ "expires_at",
20
+ "updated_at",
21
+ ]
22
+ queryset_order = ["-pk"]
23
+ allow_global_search = False
24
+
25
+ def get_list_queryset(self):
26
+ return CachedItem.objects.all().only(
27
+ "key", "created_at", "expires_at", "updated_at"
28
+ )
29
+
30
+ class DetailView(AdminModelDetailView):
31
+ model = CachedItem
32
+ title = "Cached item"
@@ -0,0 +1,40 @@
1
+ import click
2
+
3
+ from .models import CachedItem
4
+
5
+
6
+ @click.group()
7
+ def cli():
8
+ pass
9
+
10
+
11
+ @cli.command()
12
+ def clear_expired():
13
+ click.echo("Clearing expired cache items...")
14
+ result = CachedItem.objects.expired().delete()
15
+ click.echo(f"Deleted {result[0]} expired cache items.")
16
+
17
+
18
+ @cli.command()
19
+ @click.option("--force", is_flag=True)
20
+ def clear_all(force):
21
+ if not force and not click.confirm(
22
+ "Are you sure you want to delete all cache items?"
23
+ ):
24
+ return
25
+ click.echo("Clearing all cache items...")
26
+ result = CachedItem.objects.all().delete()
27
+ click.echo(f"Deleted {result[0]} cache items.")
28
+
29
+
30
+ @cli.command()
31
+ def stats():
32
+ total = CachedItem.objects.count()
33
+ expired = CachedItem.objects.expired().count()
34
+ unexpired = CachedItem.objects.unexpired().count()
35
+ forever = CachedItem.objects.forever().count()
36
+
37
+ click.echo(f"Total: {click.style(total, bold=True)}")
38
+ click.echo(f"Expired: {click.style(expired, bold=True)}")
39
+ click.echo(f"Unexpired: {click.style(unexpired, bold=True)}")
40
+ click.echo(f"Forever: {click.style(forever, bold=True)}")
@@ -0,0 +1,6 @@
1
+ from plain.packages import PackageConfig
2
+
3
+
4
+ class PlainCacheConfig(PackageConfig):
5
+ name = "plain.cache"
6
+ label = "plaincache"
@@ -0,0 +1,93 @@
1
+ from datetime import datetime, timedelta
2
+ from functools import cached_property
3
+
4
+ from plain.models import IntegrityError
5
+ from plain.utils import timezone
6
+
7
+
8
+ class Cached:
9
+ """Store and retrieve cached items."""
10
+
11
+ def __init__(self, key: str) -> None:
12
+ self.key = key
13
+
14
+ # So we can import Cached in __init__.py
15
+ # without getting the packages not ready error...
16
+ from .models import CachedItem
17
+
18
+ self._model_class = CachedItem
19
+
20
+ @cached_property
21
+ def _model_instance(self):
22
+ try:
23
+ return self._model_class.objects.get(key=self.key)
24
+ except self._model_class.DoesNotExist:
25
+ return None
26
+
27
+ def reload(self) -> None:
28
+ if hasattr(self, "_model_instance"):
29
+ del self._model_instance
30
+
31
+ def _is_expired(self):
32
+ if not self._model_instance:
33
+ return True
34
+
35
+ if not self._model_instance.expires_at:
36
+ return False
37
+
38
+ return self._model_instance.expires_at < timezone.now()
39
+
40
+ def exists(self) -> bool:
41
+ if self._model_instance is None:
42
+ return False
43
+
44
+ return not self._is_expired()
45
+
46
+ @property
47
+ def value(self):
48
+ if not self.exists():
49
+ return None
50
+
51
+ return self._model_instance.value
52
+
53
+ def set(self, value, expiration: datetime | timedelta | int | float | None = None):
54
+ defaults = {
55
+ "value": value,
56
+ }
57
+
58
+ if isinstance(expiration, int | float):
59
+ defaults["expires_at"] = timezone.now() + timedelta(seconds=expiration)
60
+ elif isinstance(expiration, timedelta):
61
+ defaults["expires_at"] = timezone.now() + expiration
62
+ elif isinstance(expiration, datetime):
63
+ defaults["expires_at"] = expiration
64
+ else:
65
+ # Keep existing expires_at value or None
66
+ pass
67
+
68
+ # Make sure expires_at is timezone aware
69
+ if defaults["expires_at"] and not timezone.is_aware(defaults["expires_at"]):
70
+ defaults["expires_at"] = timezone.make_aware(defaults["expires_at"])
71
+
72
+ try:
73
+ item, _ = self._model_class.objects.update_or_create(
74
+ key=self.key, defaults=defaults
75
+ )
76
+ except IntegrityError:
77
+ # Most likely a race condition in creating the item,
78
+ # so trying again should do an update
79
+ item, _ = self._model_class.objects.update_or_create(
80
+ key=self.key, defaults=defaults
81
+ )
82
+
83
+ self.reload()
84
+ return item.value
85
+
86
+ def delete(self) -> bool:
87
+ if not self._model_instance:
88
+ # A no-op, but a return value you can use to know whether it did anything
89
+ return False
90
+
91
+ self._model_instance.delete()
92
+ self.reload()
93
+ return True
@@ -0,0 +1,34 @@
1
+ # Generated by Plain 5.0.dev20231127233940 on 2023-12-22 03:47
2
+
3
+ from plain import models
4
+ from plain.models import migrations
5
+
6
+
7
+ class Migration(migrations.Migration):
8
+ initial = True
9
+
10
+ dependencies = []
11
+
12
+ operations = [
13
+ migrations.CreateModel(
14
+ name="CacheItem",
15
+ fields=[
16
+ (
17
+ "id",
18
+ models.BigAutoField(
19
+ auto_created=True,
20
+ primary_key=True,
21
+ serialize=False,
22
+ ),
23
+ ),
24
+ ("key", models.CharField(max_length=255, unique=True)),
25
+ ("value", models.JSONField(blank=True, null=True)),
26
+ (
27
+ "expires_at",
28
+ models.DateTimeField(blank=True, db_index=True, null=True),
29
+ ),
30
+ ("created_at", models.DateTimeField(auto_now_add=True)),
31
+ ("updated_at", models.DateTimeField(auto_now=True)),
32
+ ],
33
+ ),
34
+ ]
@@ -0,0 +1,16 @@
1
+ # Generated by Plain 5.0.dev20231127233940 on 2023-12-22 17:40
2
+
3
+ from plain.models import migrations
4
+
5
+
6
+ class Migration(migrations.Migration):
7
+ dependencies = [
8
+ ("plaincache", "0001_initial"),
9
+ ]
10
+
11
+ operations = [
12
+ migrations.RenameModel(
13
+ old_name="CacheItem",
14
+ new_name="CachedItem",
15
+ ),
16
+ ]
File without changes
@@ -0,0 +1,26 @@
1
+ from plain import models
2
+ from plain.utils import timezone
3
+
4
+
5
+ class CachedItemQuerySet(models.QuerySet):
6
+ def expired(self):
7
+ return self.filter(expires_at__lt=timezone.now())
8
+
9
+ def unexpired(self):
10
+ return self.filter(expires_at__gte=timezone.now())
11
+
12
+ def forever(self):
13
+ return self.filter(expires_at=None)
14
+
15
+
16
+ class CachedItem(models.Model):
17
+ key = models.CharField(max_length=255, unique=True)
18
+ value = models.JSONField(blank=True, null=True)
19
+ expires_at = models.DateTimeField(blank=True, null=True, db_index=True)
20
+ created_at = models.DateTimeField(auto_now_add=True)
21
+ updated_at = models.DateTimeField(auto_now=True)
22
+
23
+ objects = CachedItemQuerySet.as_manager()
24
+
25
+ def __str__(self) -> str:
26
+ return self.key
@@ -0,0 +1,17 @@
1
+ [tool.poetry]
2
+ name = "plain.cache"
3
+ packages = [
4
+ { include = "plain" },
5
+ ]
6
+ version = "0.0.0"
7
+ description = ""
8
+ authors = ["Dave Gaeddert <dave.gaeddert@dropseed.dev>"]
9
+ # readme = "README.md"
10
+
11
+ [tool.poetry.dependencies]
12
+ python = "^3.11"
13
+
14
+
15
+ [build-system]
16
+ requires = ["poetry-core"]
17
+ build-backend = "poetry.core.masonry.api"