将cURL请求转换为Python-Requests请求 [英] Convert cURL request to Python-Requests request

查看:4157
本文介绍了将cURL请求转换为Python-Requests请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要将此cURL请求转换为Python-Requests请求,因为我正在使用REST服务的Python包装器。

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

如何将它转换为Python3请求库请求?

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

到目前为止, p>

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

推荐答案

Curl命令发送特定的 multipart / form-data 字段名称; meta data API的文档指定要使用的特定元类型。

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.

此外,元数据应该编码为JSON。

Moreover, the metadata should be encoded to JSON.

b
$ b

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)

files 参数就是这里所需要的;每个值都是一个包含文件名,要发送的数据和该部件的mimetype的元组。

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.

这篇关于将cURL请求转换为Python-Requests请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆