Tastypie APIKey 认证 [英] Tastypie APIKey authentication

查看:22
本文介绍了Tastypie APIKey 认证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Tastypie APIKey 认证是如何工作的?我知道文档中提到了一个信号:

How does the Tastypie APIKey authentication work? I know there is a signal as mentioned in the documentation:

from django.contrib.auth.models import User    
from django.db import models  
from tastypie.models import create_api_key 

models.signals.post_save.connect(create_api_key, sender=User)

但是,什么时候调用?如果我想给用户他们的 APIkey,我知道我可以在 APIKey 数据库中找到它,这个 create_api_key 函数将密钥添加到其中,但是我在哪里以及何时调用这个 models.signals.post_save 函数?

However, when is this called? If I want to give a user their APIkey I know I can find it in the APIKey db that this create_api_key function adds the key into, but where and when do I call this models.signals.post_save function?

这只是另一个 django 模型吗?我觉得是吗?

Is this just another django model? I think it is?

每次保存用户帐户时都会调用它吗?

Is this called everytime a user account is saved?

推荐答案

你可以把这个放在相关应用的models.py文件中(比如main/).post_save.connect(create_api_key, sender=User) 所做的是每次保存 User 实例时,都会调用 create_api_key().

You can put this in models.py file of the relevant app (such as main/). What post_save.connect(create_api_key, sender=User) does is that everytime an User instance is saved, create_api_key() will be called.

现在让我们深入了解 美味派:

Now let's look into what create_api_key() does by diving a bit into the source of tastypie:

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 相关.当这条记录被保存到 ApiKey表.密钥由 generate_key() 函数生成.

As you can see, create_api_key() will create a new ApiKey record, which will be related to the calling User. This record will also have a HMAC key when it was saved to the ApiKey table. The key is generated by generate_key() function.

这篇关于Tastypie APIKey 认证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆