所以情况是这样的:
我有一个端点A
,该端点创建数据并对该数据调用.save()(称为functionA
),该端点还向外部第三方API发送发布请求,该请求将调用我的端点{{1 }}(称为B
)
functionB
def functionA():
try:
with transaction.atomic()
newData = Blog(title="new blog")
newData.save()
# findSavedBlog = Blog.objects.get(title="new blog")
# print(findSavedBlog)
r = requests.post('www.thirdpartyapi.com/confirm_blog_creation/',some_data) # this post request will trigger the third party to send a post request to endpoint calling functionB
return HttpResponse("Result was: " + r.status)
如果我取消注释functionA的def functionB():
blogTitle = request.POST.get('blog_title') # assume this evaluates to 'new blog'
# sleep(20)
try:
findBlog = Blog.objects.get(title=blogTitle) # again this will be the same as Blog.objects.get(title="new blog")
except ObjectDoesnotExist as e:
print("Blog not found!")
部分,它将打印保存的博客,但是functionB仍然会失败。
如果我在功能B中添加findSavedBlog
,以等待DB完成写入,然后尝试获取新创建的数据,那么它仍然会失败。
任何了解Django .save()方法和/或一些并发知识的人都可以帮助我吗?非常感激。谢谢!
编辑: 问题是我将函数A的所有内容包装在一个原子块中(最初忘记写函数A的那一部分),这意味着直到函数A返回后才提交事务!