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

否,decorator只将函数create封装在事务块中,事务也可以嵌套。事务块不会自动将父块封装在事务中。您需要在任务中创建一个事务,以确保create之外的代码在事务中运行。

以下是更多详细信息:https://docs.djangoproject.com/en/3.2/topics/db/transactions/#controlling-事务显式

一种方法:

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

最新更新