在我维护的 Django 网络应用程序中,我有一个由 Redis 驱动的排序集,其中包含所有已注册的用户名。此外,我还将所述用户名保存在 postgresql 数据库中(作为备份)。
具体来说,当用户注册时,我将他们的用户名同时保存在数据库和 Redis 中,如下所示:
def save(self, commit=True):
user = super(CreateAccountForm, self).save(commit=False)
password = self.cleaned_data["password"]
user.set_password(password)
if commit:
user.save() #saving in Postgresql DB
insert_username(self.cleaned_data.get("username")) #inserting into Redis
return user
if commit:
之后的行是操作发生的地方。
我如何确保在数据库和 Redis 中保存原子,以便在它失败的情况下,我不会留下数据完整性问题?一个说明性的例子会很棒。
最佳答案
取自here你可以这样做:
from django.db import transaction
def save(self, commit=True):
user = super(CreateAccountForm, self).save(commit=False)
password = self.cleaned_data["password"]
user.set_password(password)
if commit:
with transaction.atomic():
user.save() #saving in Postgresql DB
username = self.cleaned_data.get('username')
insert_username(username) #inserting into Redis
# We are asserting that the username has been written to redis.
# Otherwise, exception will be raised, not catched and transaction will be rolled back.
assert get_username(username) == username
return user
关于django - 在 Django 中将多个数据库后端中的数据保存为一个原子事务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42865717/