您可以将其放在models.py
相关应用程序的文件中(例如main/
)。每次保存实例时post_save.connect(create_api_key, sender=User)
都会调用它。User
create_api_key()
现在让我们通过深入研究一下 sweetpiecreate_api_key()
的来源来看看有什么作用:
class ApiKey(models.Model):
user = models.OneToOneField(User, related_name='api_key')
key = models.CharField(max_length=256, blank=True, default='')
created = models.DateTimeField(default=datetime.datetime.now)
def __unicode__(self):
return u"%s for %s" % (self.key, self.user)
def save(self, *args, **kwargs):
if not self.key:
self.key = self.generate_key()
return super(ApiKey, self).save(*args, **kwargs)
def generate_key(self):
# Get a random UUID.
new_uuid = uuid.uuid4()
# Hmac that beast.
return hmac.new(str(new_uuid), digestmod=sha1).hexdigest()
def create_api_key(sender, **kwargs):
"""
A signal for hooking up automatic ``ApiKey`` creation.
"""
if kwargs.get('created') is True:
ApiKey.objects.create(user=kwargs.get('instance'))
如您所见,create_api_key()
将创建一条ApiKey
与调用相关的新记录User
。此记录在保存到表时也将具有HMAC密钥。ApiKey
密钥由generate_key()
函数生成。