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

2024-10-03 02:44:00 发布

您现在位置: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,特别是Peers / Install Chaincode)。鉴于我之前对GET端点之一的调用工作正常,我假设我的请求有问题,有人能帮忙吗

更新:

解决方案是删除content-type头并将文件上载移到它自己的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')
    }
)

Tags: httpsiddataversionresponsetypefilespost
1条回答
网友
1楼 · 发布于 2024-10-03 02:44:00

正如提问者所承认的那样,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)

相关问题 更多 >