创建自定义用户(继承自AbstractUser
)时,我们有一个信号,该信号创建一个随机密码(来自Django的get_random_string
),并将其通过电子邮件发送给用户。
# accounts/models.py
class User(AbstractUser):
# ...
def save(self, *args, **kwargs):
if self.avatar:
self.avatar = resized_image(self.avatar, settings.SOCIAL_AVATAR_SIZE)
super().save(*args, **kwargs)
resized_image
返回from django.core.files.uploadedfile import InMemoryUploadedFile
# accounts/signals.py
@receiver(post_save, sender=User, dispatch_uid="c_employee")
def create_employee(sender, instance: User, created, **kwargs):
if not instance.has_usable_password():
password = get_random_string(length=12)
email_args = { # we're collecting information for the celery task
"password": password,
}
email_send_as_task.delay(
email_args, "Sending PASSWORD CREATE email to {{ instance.email }}"
)
if password:
logger.debug(f"CREATE PASSWORD FOR INSTANCE: {instance}")
sender.objects.filter(pk=instance.pk).update(password=make_password(password)) # .update so we don't trigger signal again
查看我的(日志记录级别DEBUG
)日志,我可以看到以下内容:
D0121 18:55:35.434 accounts.signals:81 CREATE PASSWORD FOR INSTANCE: Employee @ Example
D0121 18:55:35.641 django.db.backends:123 (0.000) UPDATE "accounts_user" SET "password" = 'pbkdf2_sha256$260000$FKRktQOZAwQ4OjcvD3QHGn$dmg9T1Y3mEwN1nbI5W2EyOAHp2chU4MGvSlaOTORNxY=' WHERE "accounts_user"."id" = 394; args=('pbkdf2_sha256$260000$FKRktQOZAwQ4OjcvD3QHGn$dmg9T1Y3mEwN1nbI5W2EyOAHp2chU4MGvSlaOTORNxY=', 394)
目前为止,一切都好。
但是,稍后在日志中,将显示此查询:
D0121 18:55:35.770 django.db.backends:123 (0.015) UPDATE "accounts_user" SET "password" = '', "last_login" = NULL, "is_superuser" = false, "username" = 'employee@example.com', "first_name" = 'First name', "last_name" = 'Employee', "email" = 'employee@example.com', "is_staff" = false, "is_active" = true, "date_joined" = '2023-01-21T17:55:35.044046+00:00'::timestamptz, "company_id" = 20, "venue_id" = 297, "avatar" = 'users/avatar.jpg', "is_admin" = false, "is_developer" = true, "role" = 'event', "allow_update" = true, "device_id" = NULL WHERE "accounts_user"."id" = 394; args=('', False, 'employee@example.com', 'First name', 'Employee', 'employee@example.com', False, True, datetime.datetime(2023, 1, 21, 17, 55, 35, 44046, tzinfo=<UTC>), 20, 297, 'users/avatar.jpg', False, True, 'event', True, 394)
因此,我的问题是:为什么密码被重新设置为空字符串?我如何调试/了解此查询的来源?
蒂亚
显然,我们在写入数据库时似乎遇到了竞争条件。似乎在信号之外调用方法不会触发对post_save
信号的另一次调用,而我们已经在信号内部。
这就是工作解决方案的样子 atm:
# accounts/signals.py
from accounts.utils import create_password
@receiver(post_save, sender=User, dispatch_uid="c_employee")
def create_employee(sender, instance: User, created, **kwargs):
if not instance.has_usable_password():
logger.debug(f"CREATE PASSWORD FOR INSTANCE: {instance}")
password = create_password(obj=instance)
email_args = { # we're collecting information for the celery task
"password": password,
}
email_send_as_task.delay(
email_args, "Sending PASSWORD CREATE email to {{ instance.email }}"
)
并在utils.py
文件中:
# accounts/utils.py
from django.utils.crypto import get_random_string
def create_password(obj=None, length=12):
password = get_random_string(length=length)
if obj is not None:
obj.set_password(password)
obj.save()
return password
我不得不推测,有一些姜戈的魔法我还没理解。不幸的是,这并没有回答标题中的问题,但使用.save()
而不是.update()
解决了我的问题。
@peter-deglopper的评论为我指明了正确的方向。谢谢!