Celery - Django - 'нулевое значение в столбце "результат" нарушает ненулевое ограничение " - PullRequest
0 голосов
/ 11 сентября 2018

Я работаю над проектом django, использующим сельдерей для постановки в очередь разных задач.В основном мы используем его для отправки почты, и у нас есть множество задач, которые в настоящее время работают по тому же методу.Дело в том, что у меня возникает ошибка на производстве, потому что вдруг сельдерей не сохраняет никаких значений в поле результата модели Task.Надеюсь, что этой информации достаточно, если нет, пожалуйста, спросите.Это обратная трассировка:

Task users.tasks.send_reset_password_task with id cf6ddab4-4407-477e-80e5-a5e50fbe4a90 raised exception:
'IntegrityError(\'null value in column "result" violates not-null constraint\\nDETAIL:  Failing row contains (524, 2018-09-10 13:26:13.528034+00, {"errors": [{"error_code": 0, "error_data": {"user_id": 3298, "e..., 3298, 59, null, null).\\n\',)'


Task was called with args: [272, [3298]] kwargs: {u'_schema_name': u'tgs'}.

The contents of the full traceback was:

Traceback (most recent call last):
  File "/app/.heroku/python/lib/python2.7/site-packages/celery/app/trace.py", line 240, in trace_task
    R = retval = fun(*args, **kwargs)
  File "/app/.heroku/python/lib/python2.7/site-packages/celery/app/trace.py", line 438, in __protected_call__
    return self.run(*args, **kwargs)
  File "/app/users/tasks.py", line 618, in send_reset_password_task
    log_event(user=user, event_type=EventLogTypes.RESET_PASSWORD_EMAIL_SENT, success=success, extra={'errors': errors})
  File "/app/lmsplatform/services_eventlog.py", line 937, in log_event
    campaign_id=campaign_id,
  File "/app/.heroku/python/lib/python2.7/site-packages/django/db/models/manager.py", line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/app/.heroku/python/lib/python2.7/site-packages/django/db/models/query.py", line 399, in create
    obj.save(force_insert=True, using=self.db)
  File "/app/.heroku/python/lib/python2.7/site-packages/django/db/models/base.py", line 796, in save
    force_update=force_update, update_fields=update_fields)
  File "/app/.heroku/python/lib/python2.7/site-packages/django/db/models/base.py", line 824, in save_base
    updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
  File "/app/.heroku/python/lib/python2.7/site-packages/django/db/models/base.py", line 908, in _save_table
    result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
  File "/app/.heroku/python/lib/python2.7/site-packages/django/db/models/base.py", line 947, in _do_insert
    using=using, raw=raw)
  File "/app/.heroku/python/lib/python2.7/site-packages/django/db/models/manager.py", line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/app/.heroku/python/lib/python2.7/site-packages/django/db/models/query.py", line 1045, in _insert
    return query.get_compiler(using=using).execute_sql(return_id)
  File "/app/.heroku/python/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 1054, in execute_sql
    cursor.execute(sql, params)
  File "/app/.heroku/python/lib/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute
    return self.cursor.execute(sql, params)
  File "/app/.heroku/python/lib/python2.7/site-packages/django/db/utils.py", line 94, in __exit__
    six.reraise(dj_exc_type, dj_exc_value, traceback)
  File "/app/.heroku/python/lib/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute
    return self.cursor.execute(sql, params)
IntegrityError: null value in column "result" violates not-null constraint
DETAIL:  Failing row contains (524, 2018-09-10 13:26:13.528034+00, {"errors": [{"error_code": 0, "error_data": {"user_id": 3298, "e..., 3298, 59, null, null).

При выполнении этой задачи:

@app.task
def send_reset_password_task(tenant_id, users):
    tenant = Service.get_tenant_by_id(tenant_id)
    tenant_config = Service.get_tenant_config(tenant)
    message_list = []
    errors = []
    success = None
    mail_connection = Service.create_mail_connection()

    with schema_context(tenant.schema_name):
        for user_id in users:
            user = User.objects.get(id=user_id)

            # Only if authentication method is PLATFORM or not PLATFORM and user is staff
            if tenant_config.users_authentication_method == 'PLATFORM' or (tenant_config.users_authentication_method != 'PLATFORM' and user.is_staff):
                tenant_domain = Service.get_tenant_domain(tenant.schema_name, protocol='https')

                uid = urlsafe_base64_encode(force_bytes(user.pk))
                token = default_token_generator.make_token(user)

                # Activate the language for this thread only
                translation.activate(user.userprofile.get_default_language())

                # Email subject *must not* contain newlines
                from_email = '%s <%s>' % (tenant.name, 'info@email.com')
                subject = _(u'%(first_name)s Recupera tu contraseña') % {'first_name': user.first_name}

                content_html = SimpleTemplateResponse("emails/reset_password.html", {
                    'user_name': user.username,
                    'user_first_name': user.first_name,
                    'tenant_domain': tenant_domain,
                    'uid': uid,
                    'token': token,
                    'tenant': tenant,
                    'lang': user.userprofile.get_default_language(),
                }, content_type="text/html", charset="utf-8").render().content

                msg = mail.EmailMessage(subject, content_html, from_email, [user.email], connection=mail_connection)
                msg.content_subtype = 'html'
                message_list.append(msg)

    try:
        mail_connection.open()
        success = mail_connection.send_messages([msg])
    except Exception as e:
        error = {'error_code': ErrorCodes.GENERAL_ERROR, 'error_data': {'user_id': user.id, 'error_detail': e.message}}
        errors.append(error)

    # Log mail result
    with schema_context(tenant.schema_name):
        log_event(user=user, event_type=EventLogTypes.RESET_PASSWORD_EMAIL_SENT, success=success, extra={'errors': errors})

Эта задача работала правильно, и теперь я сталкиваюсь с этой ошибкой при запуске этой задачи.Я не могу найти, где ошибка, я понимаю, что я не устанавливаю поле результата в модели задачи, но это должно быть сделано автоматически самим сельдереем.

...