如何使用 python 中的请求同时发送文件和表单数据?

How do I send BOTH a file and form data using requests in python?

我正在使用 python 请求库进行以下调用:

response = requests.post(
    'https://blockchain-starter.eu-gb.bluemix.net/api/v1/networks/<network id>/chaincode/install',
    headers={
        'accept':        'application/json',
        'content-type':  'multipart/form-data',
        'authorization': 'Basic  ' + b64encode(credential['key'] + ":" + credential['secret'])
    },
    data={
        'chaincode_id':      chaincode_id,
        'chaincode_version': new_version,
        'chaincode_type':    chaincode_type,
        'files':             open('chaincode.zip', 'rb')
    }
)

然而,当我打电话时,我收到 500 内部服务器错误(API 是 this, in particular Peers / Install Chaincode)。鉴于我之前对其中一个 GET 端点的调用工作正常,我认为我的请求有问题,有人可以帮忙吗?

更新:

解决方案是删除 content-type header 并将文件上传移动到它自己的 files 参数中:

response = requests.post(
    https://blockchain-starter.eu-gb.bluemix.net/api/v1/networks/<network id>/chaincode/install,
    headers={
        'accept':        'application/json',
        'authorization': 'Basic  ' + b64encode(credential['key'] + ":" + credential['secret'])
    },
    data={
        'chaincode_id':      chaincode_id,
        'chaincode_version': new_version,
        'chaincode_type':    chaincode_language
    },
    files={
        'file': open('chaincode_id.zip', 'rb')
    }
)

提问者承认,ralf htp 的回答似乎解决了他们的问题。

Do not set the Content-type header yourself, leave that to pyrequests to generate

def send_request():
payload = {"param_1": "value_1", "param_2": "value_2"}
files = {
     'json': (None, json.dumps(payload), 'application/json'),
     'file': (os.path.basename(file), open(file, 'rb'), 'application/octet-stream')
}

r = requests.post(url, files=files)
print(r.content)