如何在Django Rest Framework中使用自定义标记模型

时间:2014-11-20 15:30:11

标签: python django rest django-rest-framework

我想使用Django Rest Framework auth,但我希望为一个用户提供多个令牌。为了做到这一点,我需要实现自己的Token模型,我在Token身份验证类中找到了它:

class TokenAuthentication(BaseAuthentication):
    """
    Simple token based authentication.
    ...
    """

    model = Token
    """
    A custom token model may be used, but must have the following properties.

    * key -- The string identifying the token
    * user -- The user to which the token belongs
    """

但我不知道如何指定这个模型。我应该继承TokenAuthentication

2 个答案:

答案 0 :(得分:8)

type="submit"中定义您自己的身份验证方法:

settings.py

REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'my_project.my_app.authentication.MyOwnTokenAuthentication', ), }

authentication.py

from rest_framework.authentication import TokenAuthentication from my_project.my_app.models.token import MyOwnToken class MyOwnTokenAuthentication(TokenAuthentication): model = MyOwnToken

models.py

答案 1 :(得分:5)

该消息的含义是,模型Token可以与任何其他模型交换,只要它具有属性keyuser即可。这样,例如,如果您想要一种更复杂的方式来生成令牌密钥,您可以定义自己的模型。

因此,如果您需要自定义令牌模型,则应执行以下操作:

  1. rest_framework.authtoken.models子类化令牌模型。在此处添加您想要的任何自定义行为,但请确保它具有key属性和user属性。
  2. rest_framework.authentication对TokenAuthentication类进行子类化。将其model属性设置为您的新Token模型。
  3. 确保以您想要的任何视图引用新的身份验证类。
相关问题