【问题标题】:'str' object has no attribute 'decode' on djangorestframework_simplejwt'str' 对象在 djangorestframework_simplejwt 上没有属性 'decode'
【发布时间】:2021-07-09 09:24:28
【问题描述】:

我试图按照 djangorestframework-simplejwt 文档的快速入门链接https://django-rest-framework-simplejwt.readthedocs.io/en/latest/getting_started.html

但我在尝试获取令牌时遇到问题,并且总是返回此错误 'str' object has no attribute 'decode'

已编辑: 这是我在 urls.py 上的代码

from django.contrib import admin
from django.urls import path
from rest_framework_simplejwt import views as jwt_views
from core.views import HelloView

urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/token/', jwt_views.TokenObtainPairView.as_view(), name='token_obtain_pair'),
    path('api/token/refresh/', jwt_views.TokenRefreshView.as_view(), name='token_refresh'),
    path('hello/', HelloView.as_view(), name='hello'),
]

settings.py

...
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
]
...
REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework_simplejwt.authentication.JWTAuthentication',
    ],
}
...

views.py

from django.shortcuts import render

# Create your views here.
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated


class HelloView(APIView):
    permission_classes = (IsAuthenticated,)

    def get(self, request):
        content = {'message': 'Hello, World!'}
        return Response(content)

【问题讨论】:

  • 您需要添加您的代码。查看官方文档不会帮助找到错误
  • 好的,我会编辑这个@Neeraj
  • 你在哪里使用jwt生成的token进行认证? @MasDimas

标签: django django-rest-framework jwt


【解决方案1】:

降级 PyJWT 为我完成了这项工作。

要实现这一点,请将 requirements.txt 中的相应行更改为

PyJWT==v1.7.1

【讨论】:

    【解决方案2】:

    对我来说,让 jwt 降级到 1.7.1 版

    为此更新相应的行requirement.txt 或者如果不是 PyJWT 行,则添加此行

    PyJWT==v1.7.1
    

    【讨论】:

      【解决方案3】:

      删除“/venv/lib/python3.9/site-packages/rest_framework_jwt/utils.py”中的 .decode('utf-8') 之类的

      # /venv/lib/python3.9/site-packages/rest_framework_jwt/utils.py
      def jwt_encode_handler(payload):
      key = api_settings.JWT_PRIVATE_KEY or jwt_get_secret_key(payload)
      return jwt.encode(
          payload,
          key,
          api_settings.JWT_ALGORITHM
      )#.decode('utf-8') ==> delete this
      

      jwt2.3.0-utils-encode_handler

      当您安装 simple-jwt 时,jwt 已从 1.7.1(可能)升级到 version-2.3.0。 并由此,

      jwt2.3.0-api_jwt-encode

      "-> str:" 已添加在方法“encode”中,这意味着“encode”返回“str”。

      所以我们在 rest_framework_jwt 的 utils.py 中不再需要 .decode('utf-8')。

      如果你再次运行服务器,你可能会遇到以下问题。

      jwt.ExpiredSignature 除外: rest_framework.request.WrappedAttributeError:模块'jwt'没有属性'ExpiredSignature'

      您可以按以下方式解决此问题,

      # /venv/lib/python3.9/site-packages/rest_framework_jwt/authentication.py
      try:
          payload = jwt_decode_handler(jwt_value)
      except jwt.ExpiredSignatureError: # ExpiredSignature => no more exists
          msg = _('Signature has expired.')
          raise exceptions.AuthenticationFailed(msg)
      except jwt.DecodeError:
          msg = _('Error decoding signature.')
          raise exceptions.AuthenticationFailed(msg)
      

      jwt2.3.0-authentication-except

      出现这个问题是因为jwt-version已经升级到2.3.0,ExpiredSignature已经不存在了。

      但我们建议您将 jwt 版本降级到 1.7.1,因为我们不知道升级所做的所有更改。

      jwt2.3.0-init.py

      jwt1.7.1-init.py

      【讨论】:

      • 非常感谢这个对我有用的技巧,我使用的是 PyJWT 2.3.0
      • 很高兴听到我的回答可以帮助你:)
      【解决方案4】:

      我安装了PyJWT-2.3.0,我什至没有猜测这个问题是否与版本有关。

      以上答案帮助我解决了这个问题。所以我只是用一些额外的日志细节写了同样的东西。

      pip install PyJWT==1.7.1

      (venv) ip-192-168-1-36:django_proj rishi$ pip install PyJWT==1.7.1
      Collecting PyJWT==1.7.1
        Using cached PyJWT-1.7.1-py2.py3-none-any.whl (18 kB)
      Installing collected packages: PyJWT
        Attempting uninstall: PyJWT
          Found existing installation: PyJWT 2.3.0
          Uninstalling PyJWT-2.3.0:
            Successfully uninstalled PyJWT-2.3.0
      Successfully installed PyJWT-1.7.1
      

      我的问题终于解决了。感谢以前的答案帮助我解决这个问题。

      【讨论】:

        猜你喜欢
        • 2015-05-15
        • 1970-01-01
        • 2014-11-25
        • 2022-01-21
        • 2018-12-01
        • 2014-05-26
        • 1970-01-01
        • 2021-07-05
        • 2021-10-30
        相关资源
        最近更新 更多