首页 > 解决方案 > transaction.atomic 是否也包含被调用的函数?

问题描述

我正在使用Django / Celery,我想知道transaction.atomic我的创建函数是否也包括被调用函数(createUserTenant

这是一个示例(如您所见,我正在调用createUserTenant其中包含一些查询):

@transaction.atomic
    def create(self, request):
        formSerializer = CustomUserSerializer(data = request.data)
        if formSerializer.is_valid():
            NewUserRecord = formSerializer.save()

            if createUserTenant.delay(NewUserRecord.id, connection.schema_name):
                return Response(TeamSerializer(Team.objects.all(), many=True).data, status = status.HTTP_201_CREATED)

        return  Response(formSerializer.errors, status.HTTP_400_BAD_REQUEST)

如您所见,我在这里有一些交易

@shared_task
def createUserTenant(userid, current_schema):
    state = True
    try:
        with schema_context(current_schema):
            addUserInTeam = Team.objects.create(user = CustomUser.objects.get(pk=userid))

        with schema_context('public'):
            userInQuestion = CustomUser.objects.get(id=userid)
            # create your first real tenant
            tenant = Client(
                schema_name=str(userInQuestion.username),
                name=userInQuestion.first_name + '_' + userInQuestion.last_name,
                paid_until='2014-12-05',
                on_trial=True)
            tenant.save() 
            # migrate_schemas automatically called, your tenant is ready to be used!
            # Add one or more domains for the tenant
            domain = Domain()
            domain.domain =  str(userInQuestion.username) + settings.BASE_URL # tx.domain.com
            domain.tenant = tenant
            domain.is_primary = False
            domain.save()
    except:
        state = False
    
    return state

标签: pythondjango

解决方案


不,装饰器仅将函数包装create在事务块中,事务也可以嵌套。事务块不会自动将父块包装在事务中。您需要在您的任务中创建一个事务,以确保外部的代码create正在事务中运行。

这里有更多细节:https ://docs.djangoproject.com/en/3.2/topics/db/transactions/#controlling-transactions-explicitly

一种方法:

from django.db import transaction
@shared_task
def createUserTenant(userid, current_schema):
    with transaction.atomic():
       # your code
       # ....

推荐阅读