python - 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
解决方案
不,装饰器仅将函数包装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
# ....
推荐阅读
- c - 将 HTTP 响应中的 HTML 写入 C 中的文件
- python - 遍历 for 循环的所有列表的列表的所有组合
- react-native - navigation.getParam 不是函数。(在'navigation.getParam('message','hiiii')'中,'navigation.getParam'未定义)在本机反应中
- javascript - 为什么 Chrome 浏览器在控制台中向 navigator.appCodeName 提供“mozilla”?
- r - 使用 purrr 从嵌套的 tibble 中编写具有多个 sheetNames 的 excel 表
- python - 使用 NETCDF4 中的 MODIS 数据从 python 中的数据框中选择特定日期
- javascript - 锚链接在粘性标题后面的页面顶部。如何设置平滑滚动 JS 在滚动时始终保持 75px 的上边距?
- java - 如何从android kotlin中的recyclerview适配器获取arraylist
- html - 如何在不循环使用关键帧动画的情况下更改内容
- html - 访问时,我的网站无法在 iPhone12 pro 的谷歌应用程序中正确加载抛出一个链接