dvadmin3-celery 3.1.3__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,36 @@
1
+ """Celery result backends for Django."""
2
+ # :copyright: (c) 2016, Ask Solem.
3
+ # :copyright: (c) 2017-2033, Asif Saif Uddin.
4
+ # All rights reserved.
5
+ # :license: BSD (3 Clause), see LICENSE for more details.
6
+
7
+ import re
8
+ from collections import namedtuple
9
+
10
+ import django
11
+
12
+ __version__ = '2.5.1'
13
+ __author__ = 'Asif Saif Uddin, Ask Solem'
14
+ __contact__ = 'auvipy@gmail.com'
15
+ __homepage__ = 'https://github.com/celery/django-celery-results'
16
+ __docformat__ = 'restructuredtext'
17
+
18
+ # -eof meta-
19
+
20
+ version_info_t = namedtuple('version_info_t', (
21
+ 'major', 'minor', 'micro', 'releaselevel', 'serial',
22
+ ))
23
+
24
+ # bumpversion can only search for {current_version}
25
+ # so we have to parse the version here.
26
+ _temp = re.match(
27
+ r'(\d+)\.(\d+).(\d+)(.+)?', __version__).groups()
28
+ VERSION = version_info = version_info_t(
29
+ int(_temp[0]), int(_temp[1]), int(_temp[2]), _temp[3] or '', '')
30
+ del _temp
31
+ del re
32
+
33
+ __all__ = []
34
+
35
+ if django.VERSION < (3, 2):
36
+ default_app_config = 'django_celery_results.apps.CeleryResultConfig'
@@ -0,0 +1,83 @@
1
+ """Result Task Admin interface."""
2
+
3
+ from django.conf import settings
4
+ from django.contrib import admin
5
+ from django.utils.translation import gettext_lazy as _
6
+
7
+ try:
8
+ ALLOW_EDITS = settings.DJANGO_CELERY_RESULTS['ALLOW_EDITS']
9
+ except (AttributeError, KeyError):
10
+ ALLOW_EDITS = False
11
+ pass
12
+
13
+ from .models import GroupResult, TaskResult
14
+
15
+
16
+ class TaskResultAdmin(admin.ModelAdmin):
17
+ """Admin-interface for results of tasks."""
18
+
19
+ model = TaskResult
20
+ date_hierarchy = 'date_done'
21
+ list_display = ('task_id', 'periodic_task_name', 'task_name', 'date_done',
22
+ 'status', 'worker')
23
+ list_filter = ('status', 'date_done', 'periodic_task_name', 'task_name',
24
+ 'worker')
25
+ readonly_fields = ('date_created', 'date_done', 'result', 'meta')
26
+ search_fields = ('task_name', 'task_id', 'status', 'task_args',
27
+ 'task_kwargs')
28
+ fieldsets = (
29
+ (None, {
30
+ 'fields': (
31
+ 'task_id',
32
+ 'task_name',
33
+ 'periodic_task_name',
34
+ 'status',
35
+ 'worker',
36
+ 'content_type',
37
+ 'content_encoding',
38
+ ),
39
+ 'classes': ('extrapretty', 'wide')
40
+ }),
41
+ (_('Parameters'), {
42
+ 'fields': (
43
+ 'task_args',
44
+ 'task_kwargs',
45
+ ),
46
+ 'classes': ('extrapretty', 'wide')
47
+ }),
48
+ (_('Result'), {
49
+ 'fields': (
50
+ 'result',
51
+ 'date_created',
52
+ 'date_done',
53
+ 'traceback',
54
+ 'meta',
55
+ ),
56
+ 'classes': ('extrapretty', 'wide')
57
+ }),
58
+ )
59
+
60
+ def get_readonly_fields(self, request, obj=None):
61
+ if ALLOW_EDITS:
62
+ return self.readonly_fields
63
+ else:
64
+ return list({
65
+ field.name for field in self.opts.local_fields
66
+ })
67
+
68
+
69
+ admin.site.register(TaskResult, TaskResultAdmin)
70
+
71
+
72
+ class GroupResultAdmin(admin.ModelAdmin):
73
+ """Admin-interface for results of grouped tasks."""
74
+
75
+ model = GroupResult
76
+ date_hierarchy = 'date_done'
77
+ list_display = ('group_id', 'date_done')
78
+ list_filter = ('date_done',)
79
+ readonly_fields = ('date_created', 'date_done', 'result')
80
+ search_fields = ('group_id',)
81
+
82
+
83
+ admin.site.register(GroupResult, GroupResultAdmin)
@@ -0,0 +1,15 @@
1
+ """Application configuration."""
2
+
3
+ from django.apps import AppConfig
4
+ from django.utils.translation import gettext_lazy as _
5
+
6
+ __all__ = ['CeleryResultConfig']
7
+
8
+
9
+ class CeleryResultConfig(AppConfig):
10
+ """Default configuration for the django_celery_results app."""
11
+
12
+ name = 'django_celery_results'
13
+ label = 'django_celery_results'
14
+ verbose_name = _('Celery Results')
15
+ default_auto_field = 'django.db.models.AutoField'
@@ -0,0 +1,4 @@
1
+ from .cache import CacheBackend
2
+ from .database import DatabaseBackend
3
+
4
+ __all__ = ['CacheBackend', 'DatabaseBackend']
@@ -0,0 +1,39 @@
1
+ """Celery cache backend using the Django Cache Framework."""
2
+
3
+ from celery.backends.base import KeyValueStoreBackend
4
+ from django.core.cache import cache as default_cache
5
+ from django.core.cache import caches
6
+ from kombu.utils.encoding import bytes_to_str
7
+
8
+
9
+ class CacheBackend(KeyValueStoreBackend):
10
+ """Backend using the Django cache framework to store task metadata."""
11
+
12
+ def __init__(self, *args, **kwargs):
13
+ super().__init__(*args, **kwargs)
14
+
15
+ # Must make sure backend doesn't convert exceptions to dict.
16
+ self.serializer = 'pickle'
17
+
18
+ def get(self, key):
19
+ key = bytes_to_str(key)
20
+ return self.cache_backend.get(key)
21
+
22
+ def set(self, key, value):
23
+ key = bytes_to_str(key)
24
+ self.cache_backend.set(key, value, self.expires)
25
+
26
+ def delete(self, key):
27
+ key = bytes_to_str(key)
28
+ self.cache_backend.delete(key)
29
+
30
+ def encode(self, data):
31
+ return data
32
+
33
+ def decode(self, data):
34
+ return data
35
+
36
+ @property
37
+ def cache_backend(self):
38
+ backend = self.app.conf.cache_backend
39
+ return caches[backend] if backend else default_cache
@@ -0,0 +1,308 @@
1
+ import binascii
2
+ import json
3
+
4
+ from celery import maybe_signature
5
+ from celery.backends.base import BaseDictBackend, get_current_task
6
+ from celery.exceptions import ChordError
7
+ from celery.result import GroupResult, allow_join_result, result_from_tuple
8
+ from celery.utils.log import get_logger
9
+ from celery.utils.serialization import b64decode, b64encode
10
+ from django.db import connection, transaction
11
+ from django.db.utils import InterfaceError
12
+ from kombu.exceptions import DecodeError
13
+
14
+ from ..models import ChordCounter
15
+ from ..models import GroupResult as GroupResultModel
16
+ from ..models import TaskResult
17
+
18
+ EXCEPTIONS_TO_CATCH = (InterfaceError,)
19
+
20
+ try:
21
+ from psycopg2 import InterfaceError as Psycopg2InterfaceError
22
+ EXCEPTIONS_TO_CATCH += (Psycopg2InterfaceError,)
23
+ except ImportError:
24
+ pass
25
+
26
+ logger = get_logger(__name__)
27
+
28
+
29
+ class DatabaseBackend(BaseDictBackend):
30
+ """The Django database backend, using models to store task state."""
31
+
32
+ TaskModel = TaskResult
33
+ GroupModel = GroupResultModel
34
+ subpolling_interval = 0.5
35
+
36
+ def exception_safe_to_retry(self, exc):
37
+ """Check if an exception is safe to retry.
38
+
39
+ Backends have to overload this method with correct predicates
40
+ dealing with their exceptions.
41
+
42
+ By default no exception is safe to retry, it's up to
43
+ backend implementation to define which exceptions are safe.
44
+
45
+ For Celery / django-celery-results, retry Django / Psycopg2
46
+ InterfaceErrors, like "Connection already closed", with new connection.
47
+
48
+ Set result_backend_always_retry to True in order to enable retries.
49
+ """
50
+ for exc_type in EXCEPTIONS_TO_CATCH:
51
+ if isinstance(exc, exc_type):
52
+ # Only called if InterfaceError occurs and always_retry is True
53
+ connection.close()
54
+ return True
55
+ return False
56
+
57
+ def _get_extended_properties(self, request, traceback):
58
+ extended_props = {
59
+ 'periodic_task_name': None,
60
+ 'task_args': None,
61
+ 'task_kwargs': None,
62
+ 'task_name': None,
63
+ 'traceback': None,
64
+ 'worker': None,
65
+ }
66
+ if request and self.app.conf.find_value_for_key('extended', 'result'):
67
+
68
+ if getattr(request, 'argsrepr', None) is not None:
69
+ # task protocol 2
70
+ task_args = request.argsrepr
71
+ else:
72
+ # task protocol 1
73
+ task_args = getattr(request, 'args', None)
74
+
75
+ if getattr(request, 'kwargsrepr', None) is not None:
76
+ # task protocol 2
77
+ task_kwargs = request.kwargsrepr
78
+ else:
79
+ # task protocol 1
80
+ task_kwargs = getattr(request, 'kwargs', None)
81
+
82
+ # Encode input arguments
83
+ if task_args is not None:
84
+ _, _, task_args = self.encode_content(task_args)
85
+
86
+ if task_kwargs is not None:
87
+ _, _, task_kwargs = self.encode_content(task_kwargs)
88
+
89
+ properties = getattr(request, 'properties', {}) or {}
90
+ periodic_task_name = properties.get('periodic_task_name', None)
91
+ extended_props.update({
92
+ 'periodic_task_name': periodic_task_name,
93
+ 'task_args': task_args,
94
+ 'task_kwargs': task_kwargs,
95
+ 'task_name': getattr(request, 'task', None),
96
+ 'traceback': traceback,
97
+ 'worker': getattr(request, 'hostname', None),
98
+ })
99
+
100
+ return extended_props
101
+
102
+ def _get_meta_from_request(self, request=None):
103
+ """
104
+ Use the request or get_current_task to evaluate the `meta` attribute.
105
+
106
+ With this, is possible to assign arbitrary data in request.meta to be
107
+ retrieve and stored on the TaskResult.
108
+ """
109
+ request = request or getattr(get_current_task(), "request", None)
110
+ return getattr(request, "meta", {})
111
+
112
+ def _store_result(
113
+ self,
114
+ task_id,
115
+ result,
116
+ status,
117
+ traceback=None,
118
+ request=None,
119
+ using=None
120
+ ):
121
+ """Store return value and status of an executed task."""
122
+ content_type, content_encoding, result = self.encode_content(result)
123
+
124
+ meta = {
125
+ **self._get_meta_from_request(request),
126
+ "children": self.current_task_children(request),
127
+ }
128
+ _, _, encoded_meta = self.encode_content(
129
+ meta,
130
+ )
131
+
132
+ task_props = {
133
+ 'content_encoding': content_encoding,
134
+ 'content_type': content_type,
135
+ 'meta': encoded_meta,
136
+ 'result': result,
137
+ 'status': status,
138
+ 'task_id': task_id,
139
+ 'traceback': traceback,
140
+ 'using': using,
141
+ }
142
+
143
+ task_props.update(
144
+ self._get_extended_properties(request, traceback)
145
+ )
146
+
147
+ self.TaskModel._default_manager.store_result(**task_props)
148
+ return result
149
+
150
+ def _get_task_meta_for(self, task_id):
151
+ """Get task metadata for a task by id."""
152
+ obj = self.TaskModel._default_manager.get_task(task_id)
153
+ res = obj.as_dict()
154
+ meta = self.decode_content(obj, res.pop('meta', None)) or {}
155
+ result = self.decode_content(obj, res.get('result'))
156
+
157
+ task_args = res.get('task_args')
158
+ task_kwargs = res.get('task_kwargs')
159
+ try:
160
+ task_args = self.decode_content(obj, task_args)
161
+ task_kwargs = self.decode_content(obj, task_kwargs)
162
+ except (DecodeError, binascii.Error):
163
+ pass
164
+
165
+ # the right names are args/kwargs, not task_args/task_kwargs,
166
+ # keep both for backward compatibility
167
+ res.update(
168
+ meta,
169
+ result=result,
170
+ task_args=task_args,
171
+ task_kwargs=task_kwargs,
172
+ args=task_args,
173
+ kwargs=task_kwargs,
174
+ )
175
+ return self.meta_from_decoded(res)
176
+
177
+ def encode_content(self, data):
178
+ content_type, content_encoding, content = self._encode(data)
179
+ if content_encoding == 'binary':
180
+ content = b64encode(content)
181
+ return content_type, content_encoding, content
182
+
183
+ def decode_content(self, obj, content):
184
+ if content:
185
+ if obj.content_encoding == 'binary':
186
+ content = b64decode(content)
187
+ return self.decode(content)
188
+
189
+ def _forget(self, task_id):
190
+ try:
191
+ self.TaskModel._default_manager.get(task_id=task_id).delete()
192
+ except self.TaskModel.DoesNotExist:
193
+ pass
194
+
195
+ def cleanup(self):
196
+ """Delete expired metadata."""
197
+ self.TaskModel._default_manager.delete_expired(self.expires)
198
+ self.GroupModel._default_manager.delete_expired(self.expires)
199
+
200
+ def _restore_group(self, group_id):
201
+ """return result value for a group by id."""
202
+ group_result = self.GroupModel._default_manager.get_group(group_id)
203
+
204
+ if group_result:
205
+ res = group_result.as_dict()
206
+ decoded_result = self.decode_content(group_result, res["result"])
207
+ res["result"] = None
208
+ if decoded_result:
209
+ res["result"] = result_from_tuple(decoded_result, app=self.app)
210
+ return res
211
+
212
+ def _save_group(self, group_id, group_result):
213
+ """Store return value of group"""
214
+ content_type, content_encoding, result = self.encode_content(
215
+ group_result.as_tuple()
216
+ )
217
+ self.GroupModel._default_manager.store_group_result(
218
+ content_type, content_encoding, group_id, result
219
+ )
220
+ return group_result
221
+
222
+ def _delete_group(self, group_id):
223
+ try:
224
+ self.GroupModel._default_manager.get_group(group_id).delete()
225
+ except self.TaskModel.DoesNotExist:
226
+ pass
227
+
228
+ def apply_chord(self, header_result_args, body, **kwargs):
229
+ """Add a ChordCounter with the expected number of results"""
230
+ if not isinstance(header_result_args, GroupResult):
231
+ # Celery 5.1 provides the GroupResult args
232
+ header_result = self.app.GroupResult(*header_result_args)
233
+ else:
234
+ # celery <5.1 will pass a GroupResult object
235
+ header_result = header_result_args
236
+ results = [r.as_tuple() for r in header_result]
237
+ chord_size = body.get("chord_size", None) or len(results)
238
+ data = json.dumps(results)
239
+ ChordCounter.objects.create(
240
+ group_id=header_result.id, sub_tasks=data, count=chord_size
241
+ )
242
+
243
+ def on_chord_part_return(self, request, state, result, **kwargs):
244
+ """Called on finishing each part of a Chord header"""
245
+ tid, gid = request.id, request.group
246
+ if not gid or not tid:
247
+ return
248
+ call_callback = False
249
+ with transaction.atomic():
250
+ # We need to know if `count` hits 0.
251
+ # wrap the update in a transaction
252
+ # with a `select_for_update` lock to prevent race conditions.
253
+ # SELECT FOR UPDATE is not supported on all databases
254
+ try:
255
+ chord_counter = (
256
+ ChordCounter.objects.select_for_update()
257
+ .get(group_id=gid)
258
+ )
259
+ except ChordCounter.DoesNotExist:
260
+ logger.warning("Can't find ChordCounter for Group %s", gid)
261
+ return
262
+ chord_counter.count -= 1
263
+ if chord_counter.count != 0:
264
+ chord_counter.save(update_fields=["count"])
265
+ else:
266
+ # Last task in the chord header has finished
267
+ call_callback = True
268
+ chord_counter.delete()
269
+
270
+ if call_callback:
271
+ deps = chord_counter.group_result(app=self.app)
272
+ if deps.ready():
273
+ callback = maybe_signature(request.chord, app=self.app)
274
+ trigger_callback(
275
+ app=self.app,
276
+ callback=callback,
277
+ group_result=deps
278
+ )
279
+
280
+
281
+ def trigger_callback(app, callback, group_result):
282
+ """Add the callback to the queue or mark the callback as failed
283
+ Implementation borrowed from `celery.app.builtins.unlock_chord`
284
+ """
285
+ if group_result.supports_native_join:
286
+ j = group_result.join_native
287
+ else:
288
+ j = group_result.join
289
+
290
+ try:
291
+ with allow_join_result():
292
+ ret = j(timeout=app.conf.result_chord_join_timeout, propagate=True)
293
+ except Exception as exc: # pylint: disable=broad-except
294
+ try:
295
+ culprit = next(group_result._failed_join_report())
296
+ reason = f"Dependency {culprit.id} raised {exc!r}"
297
+ except StopIteration:
298
+ reason = repr(exc)
299
+ logger.exception("Chord %r raised: %r", group_result.id, exc)
300
+ app.backend.chord_error_from_stack(callback, ChordError(reason))
301
+ else:
302
+ try:
303
+ callback.delay(ret)
304
+ except Exception as exc: # pylint: disable=broad-except
305
+ logger.exception("Chord %r raised: %r", group_result.id, exc)
306
+ app.backend.chord_error_from_stack(
307
+ callback, exc=ChordError(f"Callback error: {exc!r}")
308
+ )