如何将PHP中的http_build_query转换为表单数据的python等价物



以下是php代码:

https://help.sender.net/knowledgebase/id-like-to-use-the-api-is-there-anything-to-help-me-get-started/

方便:

$url = "https://app.sender.net/api/";
$data = array(
"method" => "listSubscribe", 
"params" => [
"api_key" => "98844b0f8da95e7c8ace0aaa6234e4e2",
"list_id" => "12345",
"emails" => [
"name.lastname@example.com"
]
]
);
$options = [
'http' => [
'method'  => 'POST',
'content' => http_build_query(array('data' => json_encode($data)))
]
];
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);

我在python中的尝试:

import requests
myobj = {
"method": "listSubscribe", 
"params": {
"api_key": sender_api_key,
"list_id": sender_list_id,
"emails": ["email@email.com"]
}
}

r = requests.post(sender_api_url, files={'data':json.dumps(myobj)})

我已经尝试了这么多组合,并且我继续得到{"error":{"code":"002","message":"Empty request"}}作为响应。

我从r.response收到了200,所以它至少正在发送中。

当我将API密钥更改为无效时,我会得到相同的错误。

files=更改为json=data=不起的作用

解决方案是使用

r = requests.post(sender_api_url, data=dict(data=json.dumps(myobj)))

最新更新