【问题标题】:python POST requests with file + data带有文件+数据的python POST请求
【发布时间】:2015-12-09 13:32:00
【问题描述】:

我正在尝试通过需要以表单形式发送的 API 上传图片和信息。我尝试使用请求提供的“文件”选项,但没有成功。它给了我以下错误:

AttributeError: 'int' object has no attribute 'read'

我尝试的代码行是:

r = requests.post(url, headers=header, files = {'imageFile' :    open('test_pic/1.jpg'), 'ticket' : ticket}, verify=False)

弗洛里安干杯

【问题讨论】:

    标签: python python-requests multipartform-data


    【解决方案1】:
    files = {'imageFile' :    open('test_pic/1.jpg'), 'ticket' : ticket}
    

    ticket 是 int 类型的吗?我刚遇到同样的问题,文件中的值必须是str 或bytes 或bytearray 或文件对象(这将导致读取操作),请参阅请求的models.py(函数_encode_files())中的详细信息

    【讨论】:

      【解决方案2】:

      有几件事可以尝试:

      1. 如果您使用的是 Windows,请确保将 b 添加到 open 的文件权限中:

        open('filename', 'rb')
        

        这将确保文件被读取为二进制文件,否则会导致一些错误

      2. 发送多个文件时,需要传入元组列表,而不是字典:

        >>> multiple_files = [('images', ('foo.png', open('foo.png', 'rb'), 'image/png')),
                      ('images', ('bar.png', open('bar.png', 'rb'), 'image/png'))]
        >>> r = requests.post(url, files=multiple_files)
        

        这是根据online documentation。

      【讨论】:

        猜你喜欢
        • 2013-02-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-04-15
        • 1970-01-01
        • 2018-05-07
        • 1970-01-01
        • 2018-03-27
        相关资源
        最近更新 更多