Convert cURL request to Python-Requests request

与世无争的帅哥 提交于 2019-12-20 01:55:08

问题


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


回答1:


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.




回答2:


One good resource I've used for converting a cURL request to Python requests is curlconverter. You can enter your cURL request and it will format it for Python requests.

As a side note, it can also convert for PHP and Node.js.



来源:https://stackoverflow.com/questions/32585800/convert-curl-request-to-python-requests-request

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!