3
votes

Chaîne encodée en base64 non valide: le nombre de caractères de données (217) ne peut pas être supérieur à 1 et à un multiple de 4

J'apprends django et crée une application todo en l'utilisant. lors de la configuration de l'API du framework rest de django. J'obtiens une erreur inhabituelle. J'utilise django depuis un certain temps, mais je n'ai jamais eu la même erreur auparavant. Je ne sais pas pourquoi cette erreur vient.

L'erreur s'est produite la toute première fois lorsque j'ai exécuté la commande manage.py runserver et que j'ai accédé aux utilisateurs

L'erreur est comme ci-dessous

from django.contrib.auth.models import User, Group
from rest_framework import serializers


class UserSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = User
        fields = ['url', 'username', 'email', 'groups']


class GroupSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Group
        fields = ['url', 'name']

views.py

Environment:


Request Method: GET
Request URL: http://127.0.0.1:8001/users/

Django Version: 3.1
Python Version: 3.8.5
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'rest_framework',
 'todo']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']



Traceback (most recent call last):
  File "/Users/yogendrakumar/PycharmProjects/todo_app/lib/python3.8/site-packages/django/contrib/sessions/backends/base.py", line 215, in _get_session
    return self._session_cache

During handling of the above exception ('SessionStore' object has no attribute '_session_cache'), another exception occurred:
  File "/Users/yogendrakumar/PycharmProjects/todo_app/lib/python3.8/site-packages/django/contrib/sessions/backends/base.py", line 118, in decode
    return signing.loads(session_data, salt=self.key_salt, serializer=self.serializer)
  File "/Users/yogendrakumar/PycharmProjects/todo_app/lib/python3.8/site-packages/django/core/signing.py", line 135, in loads
    base64d = TimestampSigner(key, salt=salt).unsign(s, max_age=max_age).encode()
  File "/Users/yogendrakumar/PycharmProjects/todo_app/lib/python3.8/site-packages/django/core/signing.py", line 201, in unsign
    result = super().unsign(value)
  File "/Users/yogendrakumar/PycharmProjects/todo_app/lib/python3.8/site-packages/django/core/signing.py", line 184, in unsign
    raise BadSignature('Signature "%s" does not match' % sig)

During handling of the above exception (Signature "xnqTuv_ylPs2HNImqZUFHZYYDRY5IfETbWXc5_4zbB8" does not match), another exception occurred:
  File "/Users/yogendrakumar/PycharmProjects/todo_app/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner
    response = get_response(request)
  File "/Users/yogendrakumar/PycharmProjects/todo_app/lib/python3.8/site-packages/django/core/handlers/base.py", line 179, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/Users/yogendrakumar/PycharmProjects/todo_app/lib/python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
    return view_func(*args, **kwargs)
  File "/Users/yogendrakumar/PycharmProjects/todo_app/lib/python3.8/site-packages/rest_framework/viewsets.py", line 114, in view
    return self.dispatch(request, *args, **kwargs)
  File "/Users/yogendrakumar/PycharmProjects/todo_app/lib/python3.8/site-packages/rest_framework/views.py", line 505, in dispatch
    response = self.handle_exception(exc)
  File "/Users/yogendrakumar/PycharmProjects/todo_app/lib/python3.8/site-packages/rest_framework/views.py", line 465, in handle_exception
    self.raise_uncaught_exception(exc)
  File "/Users/yogendrakumar/PycharmProjects/todo_app/lib/python3.8/site-packages/rest_framework/views.py", line 476, in raise_uncaught_exception
    raise exc
  File "/Users/yogendrakumar/PycharmProjects/todo_app/lib/python3.8/site-packages/rest_framework/views.py", line 493, in dispatch
    self.initial(request, *args, **kwargs)
  File "/Users/yogendrakumar/PycharmProjects/todo_app/lib/python3.8/site-packages/rest_framework/views.py", line 410, in initial
    self.perform_authentication(request)
  File "/Users/yogendrakumar/PycharmProjects/todo_app/lib/python3.8/site-packages/rest_framework/views.py", line 324, in perform_authentication
    request.user
  File "/Users/yogendrakumar/PycharmProjects/todo_app/lib/python3.8/site-packages/rest_framework/request.py", line 220, in user
    self._authenticate()
  File "/Users/yogendrakumar/PycharmProjects/todo_app/lib/python3.8/site-packages/rest_framework/request.py", line 373, in _authenticate
    user_auth_tuple = authenticator.authenticate(self)
  File "/Users/yogendrakumar/PycharmProjects/todo_app/lib/python3.8/site-packages/rest_framework/authentication.py", line 123, in authenticate
    if not user or not user.is_active:
  File "/Users/yogendrakumar/PycharmProjects/todo_app/lib/python3.8/site-packages/django/utils/functional.py", line 240, in inner
    self._setup()
  File "/Users/yogendrakumar/PycharmProjects/todo_app/lib/python3.8/site-packages/django/utils/functional.py", line 376, in _setup
    self._wrapped = self._setupfunc()
  File "/Users/yogendrakumar/PycharmProjects/todo_app/lib/python3.8/site-packages/django/contrib/auth/middleware.py", line 23, in <lambda>
    request.user = SimpleLazyObject(lambda: get_user(request))
  File "/Users/yogendrakumar/PycharmProjects/todo_app/lib/python3.8/site-packages/django/contrib/auth/middleware.py", line 11, in get_user
    request._cached_user = auth.get_user(request)
  File "/Users/yogendrakumar/PycharmProjects/todo_app/lib/python3.8/site-packages/django/contrib/auth/__init__.py", line 174, in get_user
    user_id = _get_user_session_key(request)
  File "/Users/yogendrakumar/PycharmProjects/todo_app/lib/python3.8/site-packages/django/contrib/auth/__init__.py", line 58, in _get_user_session_key
    return get_user_model()._meta.pk.to_python(request.session[SESSION_KEY])
  File "/Users/yogendrakumar/PycharmProjects/todo_app/lib/python3.8/site-packages/django/contrib/sessions/backends/base.py", line 65, in __getitem__
    return self._session[key]
  File "/Users/yogendrakumar/PycharmProjects/todo_app/lib/python3.8/site-packages/django/contrib/sessions/backends/base.py", line 220, in _get_session
    self._session_cache = self.load()
  File "/Users/yogendrakumar/PycharmProjects/todo_app/lib/python3.8/site-packages/django/contrib/sessions/backends/db.py", line 44, in load
    return self.decode(s.session_data) if s else {}
  File "/Users/yogendrakumar/PycharmProjects/todo_app/lib/python3.8/site-packages/django/contrib/sessions/backends/base.py", line 122, in decode
    return self._legacy_decode(session_data)
  File "/Users/yogendrakumar/PycharmProjects/todo_app/lib/python3.8/site-packages/django/contrib/sessions/backends/base.py", line 126, in _legacy_decode
    encoded_data = base64.b64decode(session_data.encode('ascii'))
  File "/usr/local/Cellar/python@3.8/3.8.5/Frameworks/Python.framework/Versions/3.8/lib/python3.8/base64.py", line 87, in b64decode
    return binascii.a2b_base64(s)

Exception Type: Error at /users/
Exception Value: Invalid base64-encoded string: number of data characters (217) cannot be 1 more than a multiple of 4

Ci-dessous est traceback:

from django.contrib.auth.models import User, Group
from rest_framework import viewsets
from rest_framework import permissions
from todo.serializers import UserSerializer, GroupSerializer


class UserViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows users to be viewed or edited.
    """
    queryset = User.objects.all().order_by('-date_joined')
    serializer_class = UserSerializer
    permission_classes = [permissions.IsAuthenticated]


class GroupViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows groups to be viewed or edited.
    """
    queryset = Group.objects.all()
    serializer_class = GroupSerializer
    permission_classes = [permissions.IsAuthenticated]

serializers.py

Invalid base64-encoded string: number of data characters (217) cannot be 1 more than a multiple of 4
Request Method: GET
Request URL:    http://127.0.0.1:8001/users/
Django Version: 3.1
Exception Type: Error
Exception Value:    
Invalid base64-encoded string: number of data characters (217) cannot be 1 more than a multiple of 4
Exception Location: /usr/local/Cellar/python@3.8/3.8.5/Frameworks/Python.framework/Versions/3.8/lib/python3.8/base64.py, line 87, in b64decode
Python Executable:  /Users/yogendrakumar/PycharmProjects/todo_app/bin/python
Python Version: 3.8.5
Python Path:    
['/Users/yogendrakumar/PycharmProjects/todo_app',
 '/usr/local/Cellar/python@3.8/3.8.5/Frameworks/Python.framework/Versions/3.8/lib/python38.zip',
 '/usr/local/Cellar/python@3.8/3.8.5/Frameworks/Python.framework/Versions/3.8/lib/python3.8',
 '/usr/local/Cellar/python@3.8/3.8.5/Frameworks/Python.framework/Versions/3.8/lib/python3.8/lib-dynload',
 '/Users/yogendrakumar/PycharmProjects/todo_app/lib/python3.8/site-packages']
Server time:    Sat, 29 Aug 2020 12:25:01 +0530


5 commentaires

Il semble que le problème soit pour un champ, qui contient une chaîne base64 pour une image. Il est créé à partir de l'une des classes Serializer, lorsque cette API est appelée ( http://127.0.0.1:8001/users/ ). Veuillez partager le code de vos deux classes de sérialiseur ( c'est-à-dire UserSerializer , GroupSerializer ).


fichier serializers.py inclus


Puisque le sérialiseur semble bon, n'a pas de champ de chaîne base64 et n'a rien à voir avec votre problème, avez-vous essayé de vider votre cache et appelé à nouveau l'API?


effacé le cache, mais inutile


Code éventuellement lié.djangoproject.com/ ticket/ 31895 , code.djangoproject.com/ticket/31592


4 Réponses :


1
votes

J'ai le même problème, mais j'obtiens l'erreur quand ma version de Django est 3.0.8 et quand je la mets à niveau vers 3.1, le problème a été corrigé


0 commentaires

0
votes

Supprimer toutes les anciennes sessions de la table DJANGO_SESSION


1 commentaires

Veuillez ajouter de la clarté et du démarque à votre réponse



0
votes

J'ai oublié d'activer mon virtualenv et j'ai eu cette erreur parce que j'exécutais ce projet avec une mauvaise version de django, donc j'ai activé et cela a été résolu


0 commentaires

-2
votes

Videz le cache du navigateur et réessayez. :)


1 commentaires

Bienvenue dans StackOverflow. Lors de la rédaction d'une réponse, vous voudrez peut-être expliquer pourquoi vous pensez que votre réponse est correcte, car il se peut qu'elle ne cible pas exactement le même problème et l'explication peut aider à comprendre pourquoi