如何使用REST编写用于文件上载的Python代码?

问题描述 投票:0回答:1

我有下面的curl命令,我需要为此编写一个方法。 CURL命令:

curl -X POST "https://example.com:8443/api/rest/abc_service/123/upload/passwd" -H "accept: application/json" -H "Content-Type: multipart/form-data" -F "[email protected];type=text/plain"

我已经写了相同的下面的方法,但它失败了。码:

def upload_passwd(self):
    files = {'filename': '/root/Desktop/vdm/abhifile.txt'}
    header = {
    'Content-Type': "multipart/form-data"
    }
    self._request.headers.update(header)
    response = self._request.post(operation='upload/passwd', 
    object_id=self.object_id, files=files)

我在上面的代码中得到的REST响应是:

提供的类ABC没有可以反序列化JSON对象的JsonObject构造函数或@ ConstructorProperties带注释的构造函数

我还尝试使用以下代码更改的文件打开操作:

def upload_passwd(self):
        f = open('/root/Desktop/vdm/abhifile.txt', 'rb')

        header = {
            'Content-Type': "multipart/form-data"
        }
        self._request.headers.update(header)
        response = self._request.post(operation='upload/passwd', object_id=self.object_id,
                                      data=f)

在上面的例子中,我打开文件时出错:

ValueError:关闭文件的I / O操作

python python-2.7 rest curl multipartform-data
1个回答
0
投票

您正在使用密钥filename传递字符串,而不是传递文件的内容。

def upload_passwd(self):
    files = {'filename': open('/root/Desktop/vdm/abhifile.txt','rb')}
    header = {
    'Content-Type': "multipart/form-data"
    }
    self._request.headers.update(header)
    response = self._request.post(operation='upload/passwd', 
    object_id=self.object_id, files=files)
© www.soinside.com 2019 - 2024. All rights reserved.