重新创建curl命令,使用Python请求将JSON作为多部分/表单数据发送

Recreate curl command that sends JSON as multipart/form-data using Python-Requests

我正在尝试创建以下curl POST命令的Python-Requests版本(它可以正常运行并提供预期的响应):

1
curl -F 'json={"method":"update_video","params":{"video":{"id":"129263001","itemState":"INACTIVE"},"token":"jCoXH5OAMYQtXm1sg62KAF3ysG90YLagDAdlhg.."}}' https://api.somewebservice.com/services/post

使用:

1
curl -v -F 'json={"method":"update_video","params":{"video":{"id":"582984001","itemState":"INACTIVE"},"token":"jCoXH5OAMYQtXm1sg62KAF3ysG90YLagEECDAdlhg.."}}' https://api.somewebservice.com/services/post

我得到以下信息(仅包括所有TLS握手,服务器证书数据等之后的输出):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
....

> POST /services/post HTTP/1.1
> User-Agent: curl/7.41.0
> Host: api.somewebservice.com
> Accept: */*
> Content-Length: 294
> Expect: 100-continue
> Content-Type: multipart/form-data; boundary=------------------------871a9aa84d3c0de2
>
< HTTP/1.1 100 Continue
< HTTP/1.1 200 OK
< Content-Type: application/json;charset=UTF-8
< Content-Length: 1228
< Date: Sun, 10 Apr 2016 07:04:00 GMT
< Server: somewebservice

鉴于上述cURL命令可以正常工作,并且此输出在此处以详细模式运行,我是否正确假设我需要做的是采取一种多部分/表单方法,如果我愿意,该方法以表单形式发送JSON对象试图使用Python请求重新创建此?

到目前为止,我已经尝试过:

1
2
3
4
5
6
7
8
9
import requests
import json

def deactivate_request():
    url ="https://api.somewebservice.com/services/post"
    headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
    payload = {"method":"update_video","params":{"video":{"id":"12926301","itemState":"INACTIVE"},"token":"jCoXH5OKAF3ysG90YLagEECTP16uOUSg_fEGDAdlhg.."}}
    r = requests.post(url, json=payload, headers=headers)
    print(r.text)

我也尝试了不同的变体,例如:

1
    r = requests.post(url, data=json.dumps(payload), headers=headers)

或没有标题,例如:

1
    r = requests.post(url, data=json.dumps(payload))

或这个:

1
    r = requests.post(url, json=payload)

而且似乎没有任何效果,我只是不断收到相同的错误消息:

1
{"error": {"name":"MissingJSONError","message":"Could not find JSON-RPC.","code":211},"result": null,"id": null}

该Web服务针对" 211"错误的文档指出:

我们为json参数(对于非多篇文章)或多篇文章的第一部分得到了一个空字符串。

在使用"请求"模块重新创建此cURL请求方面,我在做什么错?我以为我可以将有效载荷对象作为形式编码的数据发送,并且看起来这就是cURL命令在此处使用-F参数所做的事情。


显然,可以使用以下命令重新创建该curl命令:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import requests

    def deactivate_request():
        url ="https://api.somewebservice.com/services/post"
        print url
        #headers = {"Authorization":"Bearer" + token,"Content-Type":"application/json"}
        headers = {'Content-Type': 'application/json'}

        print(headers)

        payload = 'json={"method":"update_video","params":{"video":{"id":"620001","itemState":"INACTIVE"},"token":"jCoXH5OAMYQtXm1sg62KAF3yECTP16uOUSg_fEGDAdlhg.."}}'
        # using params instead of data because we are making this POST request by
        # constructing query string URL with key/value pairs in it.

        r = requests.post(url, params=payload, headers=headers)

并不是很明显,因为curl命令在其标头中使用'multipart/form-data',而对于上面的命令,我们仅使用'application/json'