celery-misc 0.0.1__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,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,40 @@
1
+ Metadata-Version: 2.4
2
+ Name: celery-misc
3
+ Version: 0.0.1
4
+ Summary: Python async tools for Celery
5
+ Author: Anton Gorinenko
6
+ Author-email: anton.gorinenko@gmail.com
7
+ Keywords: python,utils,celery
8
+ Classifier: Programming Language :: Python :: 3.10
9
+ Classifier: Programming Language :: Python :: 3.11
10
+ Classifier: Programming Language :: Python :: 3.12
11
+ Classifier: Programming Language :: Python :: 3.13
12
+ Classifier: Programming Language :: Python :: 3.14
13
+ Classifier: Operating System :: OS Independent
14
+ Requires-Python: >=3.10
15
+ Description-Content-Type: text/markdown
16
+ License-File: LICENSE
17
+ Requires-Dist: celery
18
+ Requires-Dist: Django
19
+ Requires-Dist: django-celery-beat
20
+ Requires-Dist: django-json-widget
21
+ Provides-Extra: test
22
+ Requires-Dist: pytest; extra == "test"
23
+ Requires-Dist: python-dotenv; extra == "test"
24
+ Requires-Dist: envparse; extra == "test"
25
+ Requires-Dist: pytest-asyncio; extra == "test"
26
+ Requires-Dist: pytest-mock; extra == "test"
27
+ Requires-Dist: pytest-env; extra == "test"
28
+ Dynamic: author
29
+ Dynamic: author-email
30
+ Dynamic: classifier
31
+ Dynamic: description
32
+ Dynamic: description-content-type
33
+ Dynamic: keywords
34
+ Dynamic: license-file
35
+ Dynamic: provides-extra
36
+ Dynamic: requires-dist
37
+ Dynamic: requires-python
38
+ Dynamic: summary
39
+
40
+ # Python async tools for Celery
@@ -0,0 +1 @@
1
+ # Python async tools for Celery
File without changes
@@ -0,0 +1,91 @@
1
+ import logging
2
+ from django.contrib import admin
3
+ from django.contrib.admin.options import csrf_protect_m
4
+ from django.core.exceptions import ValidationError
5
+ from django.db import IntegrityError
6
+ from django.db.models import JSONField, TextField
7
+ from django.db.models.functions import Cast
8
+ from django.http import HttpResponseRedirect
9
+ from django_json_widget.widgets import JSONEditorWidget
10
+ from kombu.utils import symbol_by_name
11
+
12
+ from celery_misc.celery_monitoring import models, enums
13
+
14
+
15
+ @admin.action(description='Перезапустить задачу')
16
+ def restart_task(self, request, queryset):
17
+ """ Перезапустить задачу """
18
+ if queryset.count() > 1:
19
+ self.message_user(request, 'Необходимо выбрать только одну задачу для перезапуска.', level=logging.ERROR)
20
+ return HttpResponseRedirect(request.path)
21
+
22
+ if queryset.count() == 1:
23
+ db_task = queryset.first()
24
+ if db_task.task_status == enums.TaskStatuses.IN_PROGRESS:
25
+ self.message_user(request,
26
+ 'Выбранная задача находится в работе. Дождитесь ее завершения и повторите попытку.',
27
+ level=logging.ERROR)
28
+ return HttpResponseRedirect(request.path)
29
+
30
+ task_func = symbol_by_name(db_task.task_name)
31
+ task_func.apply_async(args=db_task.task_args, kwargs=db_task.task_kwargs)
32
+
33
+ if db_task.task_status != enums.TaskStatuses.RESTARTED:
34
+ db_task.task_status = enums.TaskStatuses.RESTARTED
35
+ db_task.save(update_fields=['task_status'])
36
+
37
+ self.message_user(request, 'Задача успешно запущена.', level=logging.INFO)
38
+ return HttpResponseRedirect(request.path)
39
+
40
+
41
+ @admin.action(description='Завершить задачи')
42
+ def kill_tasks(self, request, queryset): # pylint: disable=unused-argument
43
+ """ Завершить задачи """
44
+ queryset.update(task_status=enums.TaskStatuses.REVOKED)
45
+
46
+ self.message_user(request, 'Задачи помечены для завершения.', level=logging.INFO)
47
+ return HttpResponseRedirect(request.path)
48
+
49
+
50
+ class UserFriendlyModelAdmin(admin.ModelAdmin):
51
+ """
52
+ Вывод ошибки пользователю вместо 500 ошибки сервера в административном интерфейсе
53
+ """
54
+ formfield_overrides = {JSONField: {'widget': JSONEditorWidget}}
55
+
56
+ @csrf_protect_m
57
+ def changeform_view(self, request, object_id=None, form_url='', extra_context=None):
58
+ try:
59
+ return super().changeform_view(request, object_id, form_url, extra_context)
60
+ except (ValidationError, IntegrityError) as ex:
61
+ if hasattr(ex, 'messages') and ex.messages:
62
+ for message in ex.messages:
63
+ self.message_user(request, message, level=logging.ERROR)
64
+ elif hasattr(ex, 'message') and ex.message:
65
+ self.message_user(request, ex.message, level=logging.ERROR)
66
+ else:
67
+ self.message_user(request, str(ex), level=logging.ERROR)
68
+
69
+ return HttpResponseRedirect(request.path)
70
+
71
+
72
+ @admin.register(models.CeleryTaskInstance)
73
+ class CeleryTaskHistoryAdmin(UserFriendlyModelAdmin):
74
+ """ Admin model for CeleryTaskInstance """
75
+ formfield_overrides = {JSONField: {'widget': JSONEditorWidget}}
76
+ actions = (kill_tasks, restart_task)
77
+ list_display = ('task_id', 'task_name', 'started_at', 'finished_at', 'task_status', 'duration')
78
+ list_filter = ('task_status', 'task_name')
79
+ search_fields = ('task_id', 'task_name', 'task_args_text', 'task_kwargs_text')
80
+ ordering = ('-started_at', '-id')
81
+
82
+ def get_search_results(self, request, queryset, search_term):
83
+ """
84
+ Расширяем стандартный поиск для поиска по JSON-полю task_args
85
+ """
86
+ queryset = queryset.annotate(
87
+ task_args_text=Cast('task_args', TextField()),
88
+ task_kwargs_text=Cast('task_kwargs', TextField())
89
+ )
90
+
91
+ return super().get_search_results(request, queryset, search_term)
@@ -0,0 +1,15 @@
1
+ # pylint: disable=all
2
+ from django.apps import AppConfig
3
+
4
+
5
+ class TagsConfig(AppConfig):
6
+ """ Управление тегами """
7
+ name = 'celery_misc.celery_monitoring'
8
+ verbose_name = 'Мониторинг задач'
9
+
10
+ def ready(self):
11
+ try:
12
+ super().ready()
13
+ from celery_misc.celery_monitoring import task_signals
14
+ except ImportError:
15
+ pass
@@ -0,0 +1,10 @@
1
+ from django.db import models
2
+
3
+
4
+ class TaskStatuses(models.TextChoices):
5
+ """ Статусы задач Celery """
6
+ IN_PROGRESS = 'in_progress', 'Выполняется'
7
+ RESTARTED = 'restarted', 'Перезапущено'
8
+ DONE = 'done', 'Завершена'
9
+ ERROR = 'error', 'Ошибка выполнения'
10
+ REVOKED = 'REVOKED', 'Отозвана'
@@ -0,0 +1,38 @@
1
+ # Generated by Django 5.2.12 on 2026-03-06 06:40
2
+
3
+ import django.core.validators
4
+ from django.db import migrations, models
5
+
6
+
7
+ class Migration(migrations.Migration):
8
+
9
+ initial = True
10
+
11
+ dependencies = [
12
+ ]
13
+
14
+ operations = [
15
+ migrations.CreateModel(
16
+ name='CeleryTaskInstance',
17
+ fields=[
18
+ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
19
+ ('attempt_number', models.PositiveIntegerField(blank=True, default=0, null=True, verbose_name='Количество попыток выполнения')),
20
+ ('task_args', models.JSONField(blank=True, null=True, verbose_name='Аргументы запуска')),
21
+ ('task_kwargs', models.JSONField(blank=True, null=True, verbose_name='Параметры запуска')),
22
+ ('state', models.JSONField(blank=True, null=True, verbose_name='Состояние выполнения')),
23
+ ('result', models.JSONField(blank=True, null=True, verbose_name='Результат выполнения')),
24
+ ('profiling_cpu_result', models.TextField(blank=True, null=True, verbose_name='Результат профилирования CPU')),
25
+ ('profiling_memory_result', models.TextField(blank=True, null=True, verbose_name='Результат профилирования памяти')),
26
+ ('task_id', models.UUIDField(unique=True, verbose_name='ID задачи')),
27
+ ('task_name', models.CharField(verbose_name='Наименование задачи')),
28
+ ('started_at', models.DateTimeField(verbose_name='Дата начала выполнения')),
29
+ ('finished_at', models.DateTimeField(blank=True, null=True, verbose_name='Дата окончания выполнения')),
30
+ ('duration', models.FloatField(blank=True, null=True, validators=[django.core.validators.MinValueValidator(0.0)], verbose_name='Продолжительность выполнения задачи, сек')),
31
+ ('task_status', models.CharField(choices=[('in_progress', 'Выполняется'), ('restarted', 'Перезапущено'), ('done', 'Завершена'), ('error', 'Ошибка выполнения'), ('REVOKED', 'Отозвана')], default='in_progress', max_length=50, verbose_name='Статус выполнения задачи')),
32
+ ],
33
+ options={
34
+ 'verbose_name': 'информация о выполнении задачи',
35
+ 'verbose_name_plural': 'Информация о выполнении задачи',
36
+ },
37
+ ),
38
+ ]
@@ -0,0 +1,45 @@
1
+ from django.core.validators import MinValueValidator
2
+ from django.db import models
3
+
4
+ from celery_misc.celery_monitoring import enums, query_sets
5
+
6
+
7
+ class CeleryTaskInstance(models.Model):
8
+ """ История выполнения задач Celery """
9
+ objects = query_sets.CeleryTaskInstanceQuerySet()
10
+
11
+ attempt_number = models.PositiveIntegerField(null=True, blank=True, default=0,
12
+ verbose_name='Количество попыток выполнения')
13
+ task_args = models.JSONField(null=True, blank=True, verbose_name='Аргументы запуска')
14
+ task_kwargs = models.JSONField(null=True, blank=True, verbose_name='Параметры запуска')
15
+ state = models.JSONField(null=True, blank=True, verbose_name='Состояние выполнения')
16
+ result = models.JSONField(null=True, blank=True, verbose_name='Результат выполнения')
17
+ profiling_cpu_result = models.TextField(null=True, blank=True, verbose_name='Результат профилирования CPU')
18
+ profiling_memory_result = models.TextField(null=True, blank=True, verbose_name='Результат профилирования памяти')
19
+
20
+ task_id = models.UUIDField(unique=True, null=False, blank=False, verbose_name='ID задачи')
21
+ task_name = models.CharField(null=False, blank=False, verbose_name='Наименование задачи')
22
+ started_at = models.DateTimeField(null=False, blank=False, verbose_name='Дата начала выполнения')
23
+ finished_at = models.DateTimeField(null=True, blank=True, verbose_name='Дата окончания выполнения')
24
+ duration = models.FloatField(null=True, validators=[MinValueValidator(0.0)], blank=True,
25
+ verbose_name='Продолжительность выполнения задачи, сек')
26
+ task_status = models.CharField(max_length=50, null=False, blank=False,
27
+ choices=enums.TaskStatuses.choices,
28
+ default=enums.TaskStatuses.IN_PROGRESS,
29
+ verbose_name='Статус выполнения задачи')
30
+
31
+ def calculate_duration(self) -> float:
32
+ """ Продолжительность выполнения задачи """
33
+ if self.finished_at and self.started_at:
34
+ diff = self.finished_at - self.started_at
35
+ return diff.total_seconds()
36
+
37
+ return 0
38
+
39
+ class Meta:
40
+ """ Meta """
41
+ verbose_name = 'информация о выполнении задачи'
42
+ verbose_name_plural = 'Информация о выполнении задачи'
43
+
44
+ def __str__(self):
45
+ return f'{self.task_name} ({self.task_id})'
@@ -0,0 +1,10 @@
1
+ from celery_misc.celery_monitoring import enums
2
+ from django.db import models
3
+
4
+
5
+ class CeleryTaskInstanceQuerySet(models.QuerySet):
6
+ """ Менеджер запросов модели CeleryTaskInstance """
7
+
8
+ def get_active_tasks(self):
9
+ """ Получить активные задачи """
10
+ return self.filter(task_status=enums.TaskStatuses.IN_PROGRESS)
@@ -0,0 +1,5 @@
1
+ from django.conf import settings
2
+
3
+
4
+
5
+ settings.INSTALLED_APPS.append('django_json_widget')
@@ -0,0 +1,79 @@
1
+ import logging
2
+ import traceback
3
+
4
+ from celery.signals import task_prerun, task_postrun
5
+ from django.utils import timezone
6
+
7
+ from celery_misc import celery_utils
8
+ from celery_misc.celery_monitoring import models, enums
9
+ from celery_misc.celery_utils import cleanup_db_connections
10
+
11
+ logger = logging.getLogger(__name__)
12
+
13
+
14
+ @task_prerun.connect
15
+ @cleanup_db_connections
16
+ def register_task(task_id, task, *args, **kwargs):
17
+ """ Регистрация запущенной задачи Celery """
18
+ if _task_is_allowed(task.name, task_id):
19
+ now = timezone.now()
20
+ fields = {
21
+ 'task_args': kwargs['args'],
22
+ 'task_kwargs': kwargs['kwargs'],
23
+ 'task_name': task.name,
24
+ 'started_at': now,
25
+ 'attempt_number': 1
26
+ }
27
+ task_row, created = models.CeleryTaskInstance.objects.get_or_create(task_id=task_id, defaults=fields)
28
+ if not created:
29
+ attempt_number = task_row.attempt_number or 1
30
+ properties = {
31
+ 'task_status': enums.TaskStatuses.IN_PROGRESS,
32
+ 'started_at': now,
33
+ 'finished_at': None,
34
+ 'attempt_number': attempt_number + 1,
35
+ 'duration': 0
36
+ }
37
+
38
+ celery_utils.update_task_properties(task_row, properties)
39
+
40
+
41
+ @task_postrun.connect
42
+ @cleanup_db_connections
43
+ def finish_task(task_id, task, retval, *args, **kwargs):
44
+ """ Регистрация окончания запущенной задачи Celery """
45
+ if _task_is_allowed(task.name, task_id):
46
+ task_status = enums.TaskStatuses.DONE
47
+ task_result = {}
48
+ if retval:
49
+ if isinstance(retval, dict):
50
+ task_result = retval
51
+ elif isinstance(retval, Exception):
52
+ task_status = enums.TaskStatuses.ERROR
53
+
54
+ task_result = {
55
+ 'error': str(retval),
56
+ 'traceback': str(traceback.format_exc())
57
+ }
58
+ else:
59
+ task_result = {
60
+ 'data': str(retval)
61
+ }
62
+
63
+ _update_task_status(task.name, task_id, task_status, task_result)
64
+
65
+
66
+ def _task_is_allowed(task_name, task_id) -> bool:
67
+ return True
68
+
69
+
70
+ def _update_task_status(task_name, task_id, task_status, task_result):
71
+ task_row = models.CeleryTaskInstance.objects.filter(task_id=task_id).first()
72
+ properties = {
73
+ 'result': task_result,
74
+ 'finished_at': timezone.now()
75
+ }
76
+ if task_row.task_status != enums.TaskStatuses.REVOKED:
77
+ properties['task_status'] = task_status
78
+
79
+ celery_utils.update_task_properties(task_row, properties)
@@ -0,0 +1,93 @@
1
+ import logging
2
+ import pprint
3
+ import uuid
4
+ from functools import wraps
5
+ from typing import Any, Callable
6
+
7
+ from django import db
8
+ from django.conf import settings
9
+
10
+ from celery_misc.celery_monitoring import models, enums
11
+
12
+ logger = logging.getLogger(__name__)
13
+
14
+
15
+ def cleanup_db_connections(func):
16
+ """ Check connections """
17
+
18
+ @wraps(func)
19
+ def wrapper(*args, **kwargs):
20
+ if settings.CELERY_EAGER:
21
+ return func(*args, **kwargs)
22
+
23
+ check_connections()
24
+
25
+ try:
26
+ return func(*args, **kwargs)
27
+ except (db.OperationalError, db.InterfaceError) as exc:
28
+ logger.exception(exc)
29
+ db.close_old_connections()
30
+ try:
31
+ return func(*args, **kwargs)
32
+ except (db.OperationalError, db.InterfaceError):
33
+ raise
34
+ finally:
35
+ db.close_old_connections()
36
+
37
+ return wrapper
38
+
39
+
40
+ def check_connections():
41
+ """
42
+ Проверка соединений с Django
43
+ """
44
+ for conn in db.connections.all():
45
+ try:
46
+ cur = conn.cursor()
47
+ _ = cur.execute('SELECT 1')
48
+ except (db.OperationalError, db.InterfaceError):
49
+ conn.close()
50
+
51
+
52
+ def update_task_properties(task_obj: str | uuid.UUID | models.CeleryTaskInstance, properties: dict[str, Any]):
53
+ """ Обновление свойств задачи """
54
+ if not isinstance(task_obj, models.CeleryTaskInstance):
55
+ task_obj = models.CeleryTaskInstance.objects.filter(task_id=task_obj).first()
56
+
57
+ if task_obj:
58
+ update_fields = []
59
+ for field, value in properties.items():
60
+ if hasattr(task_obj, field):
61
+ update_fields.append(field)
62
+ setattr(task_obj, field, value)
63
+
64
+ if 'duration' not in properties:
65
+ current_duration = task_obj.calculate_duration()
66
+ if task_obj.duration:
67
+ current_duration = task_obj.duration + current_duration
68
+ task_obj.duration = current_duration
69
+ update_fields.append('duration')
70
+
71
+ task_obj.save(update_fields=update_fields)
72
+
73
+ return True
74
+
75
+ return False
76
+
77
+
78
+ @cleanup_db_connections
79
+ def common_celery_task(task, task_function: Callable, *args, **kwargs):
80
+ if args and args[0] is None:
81
+ args = list(args)
82
+ args.pop(0)
83
+
84
+ logger.debug("================ START TASK %s ================\nargs: %s\nkwargs: %s", task.name,
85
+ pprint.pformat(args), pprint.pformat(kwargs))
86
+ try:
87
+ return task_function(*args, **kwargs)
88
+ except Exception as ex: # pylint: disable=broad-except
89
+ logger.error(f'Возникла ошибка при выполнении задачи %s.', task.name)
90
+ logger.exception(ex)
91
+ raise task.retry(exc=ex)
92
+ finally:
93
+ logger.debug("================ END TASK %s ================", task.name)
@@ -0,0 +1,40 @@
1
+ Metadata-Version: 2.4
2
+ Name: celery-misc
3
+ Version: 0.0.1
4
+ Summary: Python async tools for Celery
5
+ Author: Anton Gorinenko
6
+ Author-email: anton.gorinenko@gmail.com
7
+ Keywords: python,utils,celery
8
+ Classifier: Programming Language :: Python :: 3.10
9
+ Classifier: Programming Language :: Python :: 3.11
10
+ Classifier: Programming Language :: Python :: 3.12
11
+ Classifier: Programming Language :: Python :: 3.13
12
+ Classifier: Programming Language :: Python :: 3.14
13
+ Classifier: Operating System :: OS Independent
14
+ Requires-Python: >=3.10
15
+ Description-Content-Type: text/markdown
16
+ License-File: LICENSE
17
+ Requires-Dist: celery
18
+ Requires-Dist: Django
19
+ Requires-Dist: django-celery-beat
20
+ Requires-Dist: django-json-widget
21
+ Provides-Extra: test
22
+ Requires-Dist: pytest; extra == "test"
23
+ Requires-Dist: python-dotenv; extra == "test"
24
+ Requires-Dist: envparse; extra == "test"
25
+ Requires-Dist: pytest-asyncio; extra == "test"
26
+ Requires-Dist: pytest-mock; extra == "test"
27
+ Requires-Dist: pytest-env; extra == "test"
28
+ Dynamic: author
29
+ Dynamic: author-email
30
+ Dynamic: classifier
31
+ Dynamic: description
32
+ Dynamic: description-content-type
33
+ Dynamic: keywords
34
+ Dynamic: license-file
35
+ Dynamic: provides-extra
36
+ Dynamic: requires-dist
37
+ Dynamic: requires-python
38
+ Dynamic: summary
39
+
40
+ # Python async tools for Celery
@@ -0,0 +1,20 @@
1
+ LICENSE
2
+ README.md
3
+ setup.py
4
+ celery_misc/__init__.py
5
+ celery_misc/celery_utils.py
6
+ celery_misc.egg-info/PKG-INFO
7
+ celery_misc.egg-info/SOURCES.txt
8
+ celery_misc.egg-info/dependency_links.txt
9
+ celery_misc.egg-info/requires.txt
10
+ celery_misc.egg-info/top_level.txt
11
+ celery_misc/celery_monitoring/__init__.py
12
+ celery_misc/celery_monitoring/admin.py
13
+ celery_misc/celery_monitoring/apps.py
14
+ celery_misc/celery_monitoring/enums.py
15
+ celery_misc/celery_monitoring/models.py
16
+ celery_misc/celery_monitoring/query_sets.py
17
+ celery_misc/celery_monitoring/settings.py
18
+ celery_misc/celery_monitoring/task_signals.py
19
+ celery_misc/celery_monitoring/migrations/0001_initial.py
20
+ celery_misc/celery_monitoring/migrations/__init__.py
@@ -0,0 +1,12 @@
1
+ celery
2
+ Django
3
+ django-celery-beat
4
+ django-json-widget
5
+
6
+ [test]
7
+ pytest
8
+ python-dotenv
9
+ envparse
10
+ pytest-asyncio
11
+ pytest-mock
12
+ pytest-env
@@ -0,0 +1 @@
1
+ celery_misc
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,52 @@
1
+ from os.path import dirname, join
2
+
3
+ import setuptools
4
+
5
+ LONG_DESCRIPTION = """
6
+ Python async tools for Celery
7
+ """
8
+
9
+
10
+ def long_description():
11
+ try:
12
+ return open(join(dirname(__file__), 'README.md')).read()
13
+ except IOError:
14
+ return LONG_DESCRIPTION
15
+
16
+
17
+ setuptools.setup(
18
+ name='celery-misc',
19
+ version='0.0.1',
20
+ author='Anton Gorinenko',
21
+ author_email='anton.gorinenko@gmail.com',
22
+ description='Python async tools for Celery',
23
+ long_description=long_description(),
24
+ keywords='python, utils, celery',
25
+ long_description_content_type='text/markdown',
26
+ packages=setuptools.find_packages('.', exclude=['tests', 'django_start', 'docs']),
27
+ classifiers=[
28
+ 'Programming Language :: Python :: 3.10',
29
+ 'Programming Language :: Python :: 3.11',
30
+ 'Programming Language :: Python :: 3.12',
31
+ 'Programming Language :: Python :: 3.13',
32
+ 'Programming Language :: Python :: 3.14',
33
+ 'Operating System :: OS Independent',
34
+ ],
35
+ install_requires=[
36
+ 'celery',
37
+ 'Django',
38
+ 'django-celery-beat',
39
+ 'django-json-widget'
40
+ ],
41
+ extras_require={
42
+ 'test': [
43
+ 'pytest',
44
+ 'python-dotenv',
45
+ 'envparse',
46
+ 'pytest-asyncio',
47
+ 'pytest-mock',
48
+ 'pytest-env'
49
+ ]
50
+ },
51
+ python_requires='>=3.10',
52
+ )