【问题标题】:How do I troubleshoot "Object of type BufferedReader is not JSON serializable"?如何解决“BufferedReader 类型的对象不是 JSON 可序列化的”?
【发布时间】:2021-03-23 06:10:36
【问题描述】:

我正在通过 POST 请求向我的后端发送表单数据和图像:

data = {
        'username': self.ids['username'].text,
        'email': self.email_field.text,
        'password': self.ids['password'].text,
        'data': json.dumps({
            'first_photo': open(f'{self.selfies_path}/first.png', 'rb'),
            'second_photo': open(f'{self.selfies_path}/second.png', 'rb'),
            'third_photo': open(f'{self.selfies_path}/third.png', 'rb')
        })
      }
response = requests.post('http://5.10.203.170/auth/register', files=data)

以上抛出python : TypeError: Object of type BufferedReader is not JSON serializable

我怎样才能让它工作?

【问题讨论】:

  • 你为什么要把整个文件(从open返回)分配给一个json键?考虑只发送文件的路径,前端应该能够提供它
  • this 回答你的问题了吗?

标签: python json python-requests


【解决方案1】:

您可以将文件更改为 base64

【讨论】:

    【解决方案2】:

    我去了:

    data = {
            'first_photo': open(f'{self.selfies_path}/first.png', 'rb'),
            'second_photo': open(f'{self.selfies_path}/second.png', 'rb'),
            'third_photo': open(f'{self.selfies_path}/third.png', 'rb'),
            'data': json.dumps({
                'username': self.ids['username'].text,
                'email': self.email_field.text,
                'password': self.ids['password'].text
            })
          }
    response = requests.post('http://5.10.203.170/auth/register', files=data)
    

    【讨论】:

      【解决方案3】:

      将字节转换为 base64 并在您的网站代码中解密

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-17
        • 2021-03-11
        • 2021-07-04
        • 2021-12-10
        • 1970-01-01
        相关资源
        最近更新 更多