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

查看:77
本文介绍了将 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 Requests 库请求?

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

到目前为止,我必须

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 字段名称;metadata,以及 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.

以下应该有效:

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天全站免登陆