django-optimistic-lock 2.0.0__py3-none-any.whl

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,111 @@
1
+ Metadata-Version: 2.4
2
+ Name: django-optimistic-lock
3
+ Version: 2.0.0
4
+ Summary: Offline optimistic locking for Django
5
+ Home-page: https://github.com/gavinwahl/django-optimistic-lock
6
+ Author: Gavin Wahl
7
+ Author-email: gavinwahl@gmail.com
8
+ License: BSD
9
+ Classifier: Development Status :: 4 - Beta
10
+ Classifier: Environment :: Web Environment
11
+ Classifier: Framework :: Django
12
+ Classifier: Framework :: Django :: 4.2
13
+ Classifier: Framework :: Django :: 5.0
14
+ Classifier: Framework :: Django :: 5.1
15
+ Classifier: Framework :: Django :: 5.2
16
+ Classifier: Framework :: Django :: 6.0
17
+ Classifier: Framework :: Django :: 6.1
18
+ Classifier: Intended Audience :: Developers
19
+ Classifier: License :: OSI Approved :: BSD License
20
+ Classifier: Programming Language :: Python
21
+ Classifier: Programming Language :: Python :: 3
22
+ Classifier: Programming Language :: Python :: 3.8
23
+ Classifier: Programming Language :: Python :: 3.9
24
+ Classifier: Programming Language :: Python :: 3.10
25
+ Classifier: Programming Language :: Python :: 3.11
26
+ Classifier: Programming Language :: Python :: 3.12
27
+ Classifier: Programming Language :: Python :: 3.13
28
+ Classifier: Programming Language :: Python :: 3.14
29
+ Requires-Python: >=3.8
30
+ License-File: LICENSE
31
+ Requires-Dist: django>=4.2
32
+ Dynamic: author
33
+ Dynamic: author-email
34
+ Dynamic: classifier
35
+ Dynamic: description
36
+ Dynamic: home-page
37
+ Dynamic: license
38
+ Dynamic: license-file
39
+ Dynamic: requires-dist
40
+ Dynamic: requires-python
41
+ Dynamic: summary
42
+
43
+ django-optimistic-lock
44
+ ======================
45
+
46
+ .. image:: https://github.com/gavinwahl/django-optimistic-lock/actions/workflows/test.yml/badge.svg?branch=master
47
+ :target: https://github.com/gavinwahl/django-optimistic-lock/actions/workflows/test.yml
48
+
49
+ Implements an offline optimistic lock [1]_ for Django models.
50
+
51
+
52
+ Usage
53
+ -----
54
+
55
+ Add a ``VersionField`` and inherit from ``VersionedMixin``.
56
+
57
+ .. code-block:: python
58
+
59
+ from ool import VersionField, VersionedMixin
60
+
61
+ class MyModel(VersionedMixin, models.Model):
62
+ version = VersionField()
63
+
64
+
65
+ Whenever ``MyModel`` is saved, the version will be checked to ensure
66
+ the instance has not changed since it was last fetched. If there is a
67
+ conflict, a ``ConcurrentUpdate`` exception will be raised.
68
+
69
+ Implementation
70
+ --------------
71
+ A ``VersionField`` is just an integer that increments itself every
72
+ time its model is saved. ``VersionedMixin`` overrides ``_do_update``
73
+ (which is called by ``save`` to actually do the update) to add an extra
74
+ condition to the update query -- that the version in the database is
75
+ the same as the model's version. If they match, there have been no
76
+ concurrent modifications. If they don't match, the UPDATE statement will
77
+ not update any rows, and we know that someone else saved first.
78
+
79
+ This produces SQL that looks something like::
80
+
81
+ UPDATE mymodel SET version = version + 1, ... WHERE id = %s AND version = %s
82
+
83
+ When no rows were updated, we know someone else won and we need to raise
84
+ a ``ConcurrentUpdate``.
85
+
86
+
87
+ Comparison to ``django-concurrency``
88
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
89
+ `django-concurrency <https://github.com/saxix/django-concurrency>`_ before
90
+ version 0.7 used ``SELECT FOR UPDATE`` to implement the version checking. I
91
+ wanted to avoid database-level locking, so ``django-optimistic-lock`` adds a
92
+ version filter to the update statement, as described by Martin Fowler [1]_.
93
+
94
+ Additionally, ool takes a more minimalistic approach than
95
+ django-concurrency by only doing one thing -- optimistic locking --
96
+ without any monkey-patching, middleware, settings variables, admin
97
+ classes, or form fields. django-concurrency would probably make more sense
98
+ if you're looking for something that will attempt to accommodate every
99
+ situation out of the box. Use ool if you just want a straightforward model
100
+ implementation and need to handle the UI and surrounding architecture
101
+ yourself.
102
+
103
+ Running the tests
104
+ -----------------
105
+ ::
106
+
107
+ make test
108
+
109
+
110
+ .. [1] http://martinfowler.com/eaaCatalog/optimisticOfflineLock.html
111
+ .. [2] https://code.djangoproject.com/ticket/16649
@@ -0,0 +1,6 @@
1
+ django_optimistic_lock-2.0.0.dist-info/licenses/LICENSE,sha256=GUzaIipLh20Fpp9_cR5uaZKifK7hT79lQlvbnUMWSGA,1334
2
+ ool/__init__.py,sha256=4vBLfC_sPWhOJJNtpnfkiTshzZdRiHeEoV6UCWwbXCA,4584
3
+ django_optimistic_lock-2.0.0.dist-info/METADATA,sha256=X93id-YvanILqjuHciUGjUin2NEVx6LrpZETdS1alSc,3948
4
+ django_optimistic_lock-2.0.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
5
+ django_optimistic_lock-2.0.0.dist-info/top_level.txt,sha256=2DGvTEYCAuCRjkBjzUyACNVzcSc_YuWUy4MIKggK9BQ,4
6
+ django_optimistic_lock-2.0.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,25 @@
1
+ Copyright (c) 2013, Gavin Wahl <gavinwahl@gmail.com>
2
+
3
+ All rights reserved.
4
+
5
+ Redistribution and use in source and binary forms, with or without
6
+ modification, are permitted provided that the following conditions are
7
+ met:
8
+
9
+ * Redistributions of source code must retain the above copyright
10
+ notice, this list of conditions and the following disclaimer.
11
+ * Redistributions in binary form must reproduce the above copyright
12
+ notice, this list of conditions and the following disclaimer in the
13
+ documentation and/or other materials provided with the distribution.
14
+
15
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
16
+ "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
17
+ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
18
+ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
19
+ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
20
+ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
21
+ TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
22
+ PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
23
+ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
24
+ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
ool/__init__.py ADDED
@@ -0,0 +1,126 @@
1
+ from django.db import models
2
+ from django import forms
3
+ from django.core.exceptions import ImproperlyConfigured
4
+ from django.contrib.admin.widgets import AdminIntegerFieldWidget
5
+
6
+ # Sentinel for arguments that Django only passes in some versions.
7
+ _NOT_PROVIDED = object()
8
+
9
+
10
+ class ConcurrentUpdate(Exception):
11
+ """
12
+ Raised when a model can not be saved due to a concurrent update.
13
+ """
14
+
15
+
16
+ class ReadonlyInput(forms.TextInput):
17
+ """
18
+ A HiddenInput would be perfect for version fields, but hidden
19
+ inputs leave ugly empty rows in the admin. The version must
20
+ be submitted, of course, to be checked, so we can't just use
21
+ ModelAdmin.readonly_fields.
22
+
23
+ Pending Django ticket #11277, this displays the version in an
24
+ uneditable input so there's no empty row in the admin table.
25
+
26
+ https://code.djangoproject.com/ticket/11277
27
+ """
28
+ def __init__(self, *args, **kwargs):
29
+ super(ReadonlyInput, self).__init__(*args, **kwargs)
30
+ # just readonly, because disabled won't submit the value
31
+ self.attrs['readonly'] = 'readonly'
32
+
33
+
34
+ class VersionField(models.PositiveIntegerField):
35
+ """
36
+ An integer field to track versions. Every time the model is saved,
37
+ it is incremented by one.
38
+ """
39
+
40
+ def __init__(self, *args, **kwargs):
41
+ kwargs.setdefault('default', 0)
42
+ super(VersionField, self).__init__(*args, **kwargs)
43
+
44
+ def formfield(self, **kwargs):
45
+ widget = kwargs.get('widget')
46
+ if widget:
47
+ if issubclass(widget, AdminIntegerFieldWidget):
48
+ widget = ReadonlyInput()
49
+ else:
50
+ widget = forms.HiddenInput
51
+ kwargs['widget'] = widget
52
+ return super(VersionField, self).formfield(**kwargs)
53
+
54
+
55
+ class VersionedMixin(object):
56
+ """
57
+ Model mixin implementing version checking during saving.
58
+ When a concurrent update is detected, saving is aborted and
59
+ ConcurrentUpdate will be raised.
60
+ """
61
+
62
+ def _do_update(
63
+ self,
64
+ base_qs,
65
+ using,
66
+ pk_val,
67
+ values,
68
+ update_fields,
69
+ forced_update,
70
+ returning_fields=_NOT_PROVIDED
71
+ ):
72
+ extra = {} if returning_fields is _NOT_PROVIDED else {'returning_fields': returning_fields}
73
+
74
+ version_field = self.get_version_field()
75
+
76
+ # _do_update is called once for each model in the inheritance
77
+ # hierarchy. We only care about the model with the version field.
78
+ if version_field.model != base_qs.model:
79
+ return super(VersionedMixin, self)._do_update(
80
+ base_qs, using, pk_val, values, update_fields, forced_update, **extra)
81
+
82
+ if version_field.attname in self.get_deferred_fields():
83
+ # With a deferred VersionField, it's not possible to do any
84
+ # sensible concurrency checking, so throw an error. The
85
+ # other option would be to treat deferring the VersionField
86
+ # the same as excluding it from `update_fields` -- a way to
87
+ # bypass checking altogether.
88
+ raise RuntimeError("It doesn't make sense to save a model with a deferred VersionField")
89
+
90
+ # pre_save may or may not have been called at this point, based on if
91
+ # version_field is in update_fields. Since we need to reliably know the
92
+ # old version, we can't increment there.
93
+ old_version = version_field.value_from_object(self)
94
+
95
+ # so increment it here instead. Now old_version is reliable.
96
+ for i, value_tuple in enumerate(values):
97
+ if isinstance(value_tuple[0], VersionField):
98
+ assert old_version == value_tuple[2]
99
+ values[i] = (
100
+ value_tuple[0],
101
+ value_tuple[1],
102
+ value_tuple[2] + 1,
103
+ )
104
+ setattr(self, version_field.attname, old_version + 1)
105
+
106
+ updated = super(VersionedMixin, self)._do_update(
107
+ base_qs=base_qs.filter(**{version_field.attname: old_version}),
108
+ using=using,
109
+ pk_val=pk_val,
110
+ values=values,
111
+ update_fields=update_fields if values else None, # Make sure base_qs is always checked
112
+ forced_update=forced_update,
113
+ **extra
114
+ )
115
+
116
+ if not updated and base_qs.filter(pk=pk_val).exists():
117
+ raise ConcurrentUpdate
118
+
119
+ return updated
120
+
121
+ def get_version_field(self):
122
+ for field in self._meta.fields:
123
+ if isinstance(field, VersionField):
124
+ return field
125
+ raise ImproperlyConfigured(
126
+ 'VersionedMixin models must have a VersionField')