binascii.Error:python django 中的填充不正确

我正在尝试将 base64 编码的图像保存在 django rest 框架中。首先,我们做一个代码,将base64编码后的图片插入到imagefield中进行测试,出现如下错误。

binascii.Error:填充不正确

我不明白的是,我之前使用过相同的代码并没有出现这样的错误。你能帮助我吗?这是我的代码。

serializers.py

from rest_framework import serializers

from .models import post, comment


class Base64ImageField (serializers.ImageField) :


    def to_internal_value (self, data) :

        from django.core.files.base import ContentFile

        import base64

        import six

        import uuid


        if isinstance(data, six.string_types):

            if 'data:' in data and ';base64,' in data :

                header, data = data.split(';base64,')


            try :

                decoded_file = base64.b64decode(data)

            except TypeError :

                self.fail('invalid_image')


            file_name = str(uuid.uuid4())[:12]

            file_extension = self.get_file_extension(file_name, decoded_file)

            complete_file_name = "%s.%s" % (file_name, file_extension, )

            data = ContentFile(decoded_file, name=complete_file_name)


        return super(Base64ImageField, self).to_internal_value(data)


    def get_file_extension (self, file_name, decoded_file) :

        import imghdr


        extension = imghdr.what(file_name, decoded_file)

        extension = "jpg" if extension == "jpeg" else extension


        return extension


class commentSerializer (serializers.ModelSerializer) :


    class Meta :

        model = comment

        fields = '__all__'


class postSerializer (serializers.ModelSerializer) :

    author = serializers.CharField(source='author.username', read_only=True)

    image1 = Base64ImageField(use_url=True)

    image2 = Base64ImageField(use_url=True)

    image3 = Base64ImageField(use_url=True)

    image4 = Base64ImageField(use_url=True)

    image5 = Base64ImageField(use_url=True)

    comment = commentSerializer(many=True, read_only=True)


    class Meta:

        model = post

        fields = ['pk', 'author', 'title', 'text', 'image1', 'image2', 'image3', 'image4', 'image5', 'tag1', 'tag2', 'tag3', 'tag4', 'tag5', 'comment']


汪汪一只猫
浏览 156回答 5
5回答

梵蒂冈之花

我不确定这是否适用于您的情况,具体取决于您存储编码数据的位置。我有同样的错误,但它与一些编码的会话数据有关。我清除了浏览器 Devtools 中的会话数据(cookie、缓存等),它解决了我的问题。只是张贴它以防它适用或帮助其他出于同样原因而来的人。

交互式爱情

在 shell 中运行以下命令from django.contrib.sessions.models import Session Session.objects.all().delete()

慕森卡

我有同样的错误。我做了所有清除缓存的事情,但它不起作用。现在将浏览器更改为 Mozilla。现在它正在工作。

MM们

我遇到过同样的问题。我猜这是因为我一开始使用的是 django 4.0.1,后来切换回 django 2.2...(也许你的问题不是由此引起的,但我只是想提供一些关于问题可能出在哪里的想法遇到此问题的读者请访问此页面。)session_dataDjango 4.0.1 应该直接将字符串中的会话数据保存到数据库中,但是 Django 2.2 将 base64 编码的数据保存到数据库表的同一列中/从中读取django_session。在我的例子中,base64.b64decode() 中失败的字符串是.eJxVjEEOwiAQRe_C2pABCgWX7j0DmRlAqoYmpV0Z765NutDtf-_9l4i4rTVuPS9xSuIslDj9boT8yG0H6Y7tNkue27pMJHdFHrTL65zy83K4fwcVe_3WGtkEHfLg2IMroL1VZA0BFGMJPJhRkdEucypY2CfA7C2HgRHGor14fwDNWjfC:1nERxl:5jJRHXpQH7aZrf2-C99MnTIWARd_cUag76Xa2YjW1yw,这显然不是有效的 base64 字符串,因为:&nbsp;-&nbsp;.&nbsp;.base64 字符列表中根本不存在符号。我的完整回溯信息是:Internal Server Error: /adminTraceback (most recent call last):&nbsp; File "C:\Users\Public\django2.2\lib\site-packages\django\contrib\sessions\backends\base.py", line 189, in _get_session&nbsp; &nbsp; return self._session_cacheAttributeError: 'SessionStore' object has no attribute '_session_cache'During handling of the above exception, another exception occurred:Traceback (most recent call last):&nbsp; File "C:\Users\Public\django2.2\lib\site-packages\django\core\handlers\exception.py", line 34, in inner&nbsp; &nbsp; response = get_response(request)&nbsp; File "C:\Users\Public\django2.2\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response&nbsp; &nbsp; response = self.process_exception_by_middleware(e, request)&nbsp; File "C:\Users\Public\django2.2\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response&nbsp; &nbsp; response = wrapped_callback(request, *callback_args, **callback_kwargs)&nbsp; File "C:\Users\Public\django2.2\lib\site-packages\django\contrib\admin\sites.py", line 241, in wrapper&nbsp; &nbsp; return self.admin_view(view, cacheable)(*args, **kwargs)&nbsp; File "C:\Users\Public\django2.2\lib\site-packages\django\utils\decorators.py", line 142, in _wrapped_view&nbsp; &nbsp; response = view_func(request, *args, **kwargs)&nbsp; File "C:\Users\Public\django2.2\lib\site-packages\django\views\decorators\cache.py", line 44, in _wrapped_view_func&nbsp; &nbsp; response = view_func(request, *args, **kwargs)&nbsp; File "C:\Users\Public\django2.2\lib\site-packages\django\contrib\admin\sites.py", line 212, in inner&nbsp; &nbsp; if not self.has_permission(request):&nbsp; File "C:\Users\Public\django2.2\lib\site-packages\django\contrib\admin\sites.py", line 186, in has_permission&nbsp; &nbsp; return request.user.is_active and request.user.is_staff&nbsp; File "C:\Users\Public\django2.2\lib\site-packages\django\utils\functional.py", line 256, in inner&nbsp; &nbsp; self._setup()&nbsp; File "C:\Users\Public\django2.2\lib\site-packages\django\utils\functional.py", line 392, in _setup&nbsp; &nbsp; self._wrapped = self._setupfunc()&nbsp; File "C:\Users\Public\django2.2\lib\site-packages\django\contrib\auth\middleware.py", line 24, in <lambda>&nbsp; &nbsp; request.user = SimpleLazyObject(lambda: get_user(request))&nbsp; File "C:\Users\Public\django2.2\lib\site-packages\django\contrib\auth\middleware.py", line 12, in get_user&nbsp; &nbsp; request._cached_user = auth.get_user(request)&nbsp; File "C:\Users\Public\django2.2\lib\site-packages\django\contrib\auth\__init__.py", line 182, in get_user&nbsp; &nbsp; user_id = _get_user_session_key(request)&nbsp; File "C:\Users\Public\django2.2\lib\site-packages\django\contrib\auth\__init__.py", line 59, in _get_user_session_key&nbsp; &nbsp; return get_user_model()._meta.pk.to_python(request.session[SESSION_KEY])&nbsp; File "C:\Users\Public\django2.2\lib\site-packages\django\contrib\sessions\backends\base.py", line 54, in __getitem__&nbsp; &nbsp; return self._session[key]&nbsp; File "C:\Users\Public\django2.2\lib\site-packages\django\contrib\sessions\backends\base.py", line 194, in _get_session&nbsp; &nbsp; self._session_cache = self.load()&nbsp; File "C:\Users\Public\django2.2\lib\site-packages\django\contrib\sessions\backends\db.py", line 44, in load&nbsp; &nbsp; return self.decode(s.session_data) if s else {}&nbsp; File "C:\Users\Public\django2.2\lib\site-packages\django\contrib\sessions\backends\base.py", line 100, in decode&nbsp; &nbsp; encoded_data = base64.b64decode(session_data.encode('ascii'))

慕桂英546537

您可能在不同的环境中运行服务器,激活该环境并尝试再次运行服务器。如果 env 文件夹在您当前的路径中,请执行以下操作杀死服务器然后运行source&nbsp;env/bin/activate python&nbsp;manage.py&nbsp;runserver
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python