手动令牌与Django Rest框架JWT

问题描述:

我目前正在使用Django Rest Framework JWT进行项目验证。我已经实现了BasicAuthentication,SessionAuthentication和JSONWebTokenAuthentication,用户可以通过使用POST方法为每个新会话请求令牌。但是,我希望在创建每个用户后立即创建令牌(并可能在管理员部分中查看)。手动令牌与Django Rest框架JWT

我看了一下Django的REST框架JWT文档它指出,令牌可以使用手动创建:

from rest_framework_jwt.settings import api_settings 

jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER 
jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER 

payload = jwt_payload_handler(user) 
token = jwt_encode_handler(payload) 

我试图把这个代码片断在views.py,models.py和序列化。 py,但我不断收到“用户”的参考错误。

任何有关如何正确实现此代码段或替代方法的帮助将不胜感激。谢谢

我没有按照正式文档的例子。因为我得到了第二和第三行的错误。我的配置在我的设置路径中引发了一个例外。

我直接从库本身调用函数。

from rest_framework_jwt.utils import jwt_payload_handler, jwt_encode_handler 

假设我的函数取1个字典作为输入,并返回token

from rest_framework_jwt.utils import jwt_payload_handler, jwt_encode_handler 

def create_token(platform_data: typing.Dict): 
    """ 
    System will search from userprofile model 
    Then create user instance 
    :param platform_data: 
    :return: 
    """ 
    # If found `userprofile `in the system use the existing 
    # If not create new `user` and `userprofile` 

    platform_id = platform_data.get('id') # Can trust this because it is primary key 
    email = platform_data.get('email') # This is user input should not trust 

    userprofile_qs = UserProfile.objects.filter(platform_id=platform_id) 
    if userprofile_qs.exists(): 
     # user exists in the system 
     # return Response token 
     userprofile = userprofile_qs.first() 
     user = userprofile.user 
    else: 
     # Create user and then bind it with userprofile 
     user = User.objects.create(
      username=f'poink{platform_id}', 
     ) 
    user.email = email # Get latest email 
    user.save() 
    UserProfile.objects.create(
     platform_id=platform_id, 
     user=user, 
    ) 

    payload = jwt_payload_handler(user) 
    token = jwt_encode_handler(payload) 
    return token 

希望得到的想法从这个