S
S
skorpix2016-07-26 11:53:56
Django
skorpix, 2016-07-26 11:53:56

Django how to make transactions for checkout?

Good day!
Base - Postresql
There is a view from CreateView
An order is created in it.
Something like this:

def form_valid(self, form):
    with transaction.atomic():
        order = form.save(commit=False)
        order.status = 'processed'
        # некоторые изменения полей order
        order.save()
        transaction.on_commit(lambda: create_order_print_archive.delay(order.pk))
    return self.render_to_response(self.get_context_data(form=form, order=order, payment_form=payment_form))

In the create_order_print_archive task, images are generated and saved (a relatively time-consuming task)
@task
def create_order_print_archive(order_pk):
    order = Order.objects.get(pk=int(order_pk))
    # генерация изображений
    args = [
        'node', full_path_to_js, order_item_image.image.path, str(print_width), str(print_height),
        str(editor_width), str(editor_height), page_json, site_domain
    ]
    process = Popen(args, stdin=PIPE, stdout=PIPE, stderr=PIPE)
    output, errors = process.communicate()
    if errors:
        raise NodeJSError(errors)
    process.wait()
    order.status = 'new'
    order.save()
    return True

But! Sometimes (just sometimes, it's not possible to catch it yet) The following happens: the view is executed, the order is created, the task is executed, but the changes made to the task are not saved. I logged the states in the task: after saving, I got the order again by id and displayed the status and it was 'new'. Apparently, somewhere there is a transaction rollback or something like that.
I don't even know which way to dig. In the dock, if I understand correctly, it is necessary to write exactly like this.
Can you tell me how to save orders? Or what am I doing wrong?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question