在Django

时间:2017-03-17 19:31:17

标签: django django-models redis

在我维护的Django Web应用程序中,我有一个Redis驱动的有序集,其中包含所有已注册的用户名。此外,我还将所述用户名保存在postgresql DB中(作为备份)。

具体来说,当用户注册时,我会在DB和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:之后的行是行动发生的地方。

如何确保在DB中保存并且Redis发生原子,以便在失败的情况下,我没有留下数据完整性问题?一个说明性的例子会很棒。

1 个答案:

答案 0 :(得分:2)

取自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