from .exceptions import InvalidKeyError ModuleNotFoundError: No module named 'jwt.exceptions'

3.7k Views Asked by At

I am trying to send an email verification link to a registered user but i keep getting this error, i dont know why but anytime i send a post request to this endpoint i keep getting this error

Internal Server Error: /auth/register                                                                                                                                    
Traceback (most recent call last):                                                                                                                                       
  File "/mnt/c/Users/Somtochukwu/Desktop/cultural-exchange/proj/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner                        
    response = get_response(request)                                                                                                                                     
  File "/mnt/c/Users/Somtochukwu/Desktop/cultural-exchange/proj/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response                    
    response = wrapped_callback(request, *callback_args, **callback_kwargs)                                                                                              
  File "/mnt/c/Users/Somtochukwu/Desktop/cultural-exchange/proj/lib/python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view                   
    return view_func(*args, **kwargs)                                                                                                                                    
  File "/mnt/c/Users/Somtochukwu/Desktop/cultural-exchange/proj/lib/python3.8/site-packages/django/views/generic/base.py", line 70, in view                              
    return self.dispatch(request, *args, **kwargs)                                                                                                                       
  File "/mnt/c/Users/Somtochukwu/Desktop/cultural-exchange/proj/lib/python3.8/site-packages/rest_framework/views.py", line 509, in dispatch                              
    response = self.handle_exception(exc)                                                                                                                                
  File "/mnt/c/Users/Somtochukwu/Desktop/cultural-exchange/proj/lib/python3.8/site-packages/rest_framework/views.py", line 469, in handle_exception                      
    self.raise_uncaught_exception(exc)                                                                                                                                   
  File "/mnt/c/Users/Somtochukwu/Desktop/cultural-exchange/proj/lib/python3.8/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception              
    raise exc                                                                                                                                                            
  File "/mnt/c/Users/Somtochukwu/Desktop/cultural-exchange/proj/lib/python3.8/site-packages/rest_framework/views.py", line 506, in dispatch                              
    response = handler(request, *args, **kwargs)                                                                                                                         
  File "/mnt/c/Users/Somtochukwu/Desktop/cultural-exchange/SRC/users/views.py", line 28, in post                                                                         
    print(token)                                                                                                                                                         
  File "/mnt/c/Users/Somtochukwu/Desktop/cultural-exchange/proj/lib/python3.8/site-packages/rest_framework_simplejwt/tokens.py", line 80, in __str__                     
    from .state import token_backend                                                                                                                                     
  File "/mnt/c/Users/Somtochukwu/Desktop/cultural-exchange/proj/lib/python3.8/site-packages/rest_framework_simplejwt/state.py", line 3, in <module>                      
    from .backends import TokenBackend                                                                                                                                   
  File "/mnt/c/Users/Somtochukwu/Desktop/cultural-exchange/proj/lib/python3.8/site-packages/rest_framework_simplejwt/backends.py", line 3, in <module>                   
    from jwt import InvalidAlgorithmError, InvalidTokenError, algorithms                                                                                                 
  File "/mnt/c/Users/Somtochukwu/Desktop/cultural-exchange/proj/lib/python3.8/site-packages/jwt/algorithms.py", line 5, in <module>                                      
    from .exceptions import InvalidKeyError                                                                                                                              
ModuleNotFoundError: No module named 'jwt.exceptions'  

Here is my views.py

class RegisterView(GenericAPIView):
    serializer_class = RegisterSerializer

    def post(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        if serializer.is_valid():
            serializer.save()
            user_data = serializer.data 
            user = User.objects.get(email=user_data['email'])
            token = RefreshToken.for_user(user).access_token
            print(token)
            current_site = get_current_site(request).domain
            relative_link = reverse('verify')
            absurl = 'http://'+ current_site + relative_link + "?token=" + str(token)
            email_body = f"Hi {user_name}. Use the link below to verify your email \n {absurl}" 
            email = send_mail("Account confirmation mail", email_body, settings.EMAIL_HOST_USER, [user.email])
            

            return Response(user_data, status=status.HTTP_201_CREATED)
        else:
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


i had JWT installed before i kept getting the error

here is my pip list

Package                       Version                                                                                                                                    
----------------------------- -------                                                                                                                                    
asgiref                       3.3.4                                                                                                                                      
cffi                          1.14.5                                                                                                                                     
cryptography                  3.4.7                                                                                                                                      
Django                        3.2                                                                                                                                        
django-braces                 1.14.0                                                                                                                                     
django-countries              7.1                                                                                                                                        
django-rest-framework         0.1.0                                                                                                                                      
djangorestframework           3.12.4                                                                                                                                     
djangorestframework-simplejwt 4.6.0                                                                                                                                      
Pillow                        8.2.0                                                                                                                                      
pip                           21.0.1                                                                                                                                     
pycparser                     2.20                                                                                                                                       
PyJWT                         2.0.1                                                                                                                                      
pytz                          2021.1                                                                                                                                     
setuptools                    54.1.2                                                                                                                                     
six                           1.15.0                                                                                                                                     
sqlparse                      0.4.1                                                                                                                                      
wheel                         0.36.2

Please what is the cause of this error and how can i solve it

4

There are 4 best solutions below

2
On

You should add this to settings.py

REST_FRAMEWORK = {
    ...
    'DEFAULT_AUTHENTICATION_CLASSES': (
        ...
        'rest_framework_simplejwt.authentication.JWTAuthentication',
    )
    ...
}

according to the docs

1
On

Django is confusing between modules 'jwt' and PyJWT. To avoid this confusion uninstall both modules. Now, install jwt first and then install PyJWT.

pip install jwt
pip install pyjwt

Order of installation matters

0
On

instead of using:

token = RefreshToken.for_user(user).access_token

use :

from rest_framework_simplejwt.tokens import AccessToken

token = AccessToken.for_user(user)

it works for me

0
On

I am adding an answer to this for future reference. As previously noted by another user Django is confusing between modules jwt and PyJWT. You must uninstall both modules and then reinstall PyJWT.

pip install jwt
pip install pyjwt

You also need to add the following code to settings.py.

REST_FRAMEWORK = {
    ...
    'DEFAULT_AUTHENTICATION_CLASSES': (
        ...
        'rest_framework_simplejwt.authentication.JWTAuthentication',
    )
    ...
}

I have however found that in my own application, this did not fully suffice. Despite launching the Django application in a dedicated virtual environment, it would default to the global python environment. This was an odd interaction I found, and required some time to fix. For a quick and easier fix to this issue follow the uninstall and install instructions on the global environment, however, this isn't best practice. It is best to ensure Django is running within the intended environment.