python2模拟curl发送请求,将cURL请求转换为Python-Requests请求

I want to convert this cURL request to a Python-Requests request since I am working on a Python wrapper for a REST service

MS_WORD_DOCUMENT=...

CONTENT_TYPE="application/msword"

JSON_REQUEST="{\"documentType\" : \"$CONTENT_TYPE\"}"

curl -X POST -F "meta=$JSON_REQUEST;type=application/json" -F "data=@$MS_WORD_DOCUMENT" $SERVICE_ENDPOINT

How can I convert this to a Python3 Requests library request?

So far I've got to

data = {"metadata": {"documentType": "application/msword",

"Content-Type": "application/json"}}

req = requests.post(

"https://text.s4.ontotext.com/v1/twitie",

auth=("user", "pass"),

headers={"Content-Type": "multipart/mixed"},

data=data,

files={"file": ("sample.docx", content,

"application/octet-stream")})

I don't know if that's the way to process multipart requests of the type with requests

解决方案

The Curl command sends specific multipart/form-data field names; meta and data, and the documentation for the API specifies specific meta-types to be used.

Moreover, the metadata should be encoded to JSON.

The following should work:

import json

import requests

metadata = json.dumps({"documentType": "application/msword"})

files = {

'meta': ('', metadata, 'application/json'),

'data': ('sample.docx', content, 'application/octet-stream'),

}

req = requests.post(

"https://text.s4.ontotext.com/v1/twitie",

auth=("user", "pass"),

files=files)

The files parameter is all that is needed here; each value is a tuple with a filename, the data to be sent, and the mimetype for that part.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值