django - 并发问题还是其他?.save() 方法 + DB 时序
问题描述
所以情况是这样的:我有一个端点A
,它创建数据并在该数据上调用 .save() (调用 this functionA
),它还会向外部 3rd 方 API 发送一个发布请求,该 API 将调用我的端点B
(调用 this 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)
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!")
如果我取消注释findSavedBlog
functionA 的部分,它将打印保存的博客,但 functionB 仍然会失败。
如果我在sleep
函数 B 中添加一个以等待数据库完成写入然后尝试获取新创建的数据,它仍然会失败。
任何了解 Django 的 .save() 方法和/或一些并发知识的人都可以在这里帮助我吗?非常感激。谢谢!
编辑: 问题是我将所有 functionA 包装在一个原子块中(最初忘记编写 functionA 的那部分),这意味着在 functionA 返回之前事务不会提交!