django - 使用transaction.atomic()上下文管理器 - 捕获异常

时间:2017-05-03 14:46:37

标签: python django logging django-orm django-database

我尝试使用transation.commit()上下文管理器记录数据库错误。 这是代码块:

def _process_batch(_lower_limit, _upper_limit, step, **kwargs):
        skipped_rows_mapping = kwargs.pop('skipped_rows_mapping')
        form_errors = kwargs.pop('form_errors')
        process_rows_object_list = _process_rows(
            _lower_limit, _upper_limit, **process_rows_kwargs
        )
        try:
            with transaction.atomic():
                Transcript.objects.bulk_create(process_rows_object_list, batch_size=2000)
            if verbose:
                print('processed {} rows; {} transcripts created...'.format(
                    upper_limit, len(process_rows_object_list))
                )
                print_timestamp()

            # periodically log errors to logfiles
            for _key, _vals in skipped_rows_mapping.items():
                with open(_vals['logfile'], 'a+') as logfile:
                    _writer = csv.writer(logfile, delimiter=str('|'))
                    _writer.writerows(
                        [r + (_vals['msg'],) for r in _vals['lst']]
                    )
                    skipped_rows_mapping[_key]['lst'] = []
            if form_errors.keys():
                with open("/tmp/process_transcripts_with_temp_db_table_form_errors", 'a+') as log_file:
                    for _form_err, _rows_ in form_errors.items():
                        _writer = csv.writer(log_file, delimiter=str('|'))
                        _writer.writerows(
                            [_r + (_form_err,) for _r in _rows_]
                        )
                        form_errors[_form_err] = list()

        except (IntegrityError, DatabaseError) as db_exception:
            errors_list.append(
                ErrorDetails(
                    err_type=db_exception.__class__.__name__,
                    msg=db_exception.message, id_interval=(_lower_limit, _upper_limit)
                )
            )
        finally:
            _lower_limit = _upper_limit
            _upper_limit += step
            if _upper_limit > max_id:
                _upper_limit = max_id
            return _lower_limit, _upper_limit

但是,IntegrityErrorDatabaseError未被捕获,可能是因为with transaction.atomic()块已经处理了异常。

我如何修改代码以捕获并记录这些错误?

0 个答案:

没有答案