如何将 PHP cURL 请求转换为 python

How do I translate a PHP cURL request to python

我正在编写一个工具来获取 Whois 信息,我需要为此使用 WHMCS API。

这是他们提供的代码:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://www.example.com/includes/api.php');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,
    http_build_query(
        array(
            'action' => 'DomainGetWhoisInfo',
            // See https://developers.whmcs.com/api/authentication
            'username' => 'IDENTIFIER_OR_ADMIN_USERNAME',
            'password' => 'SECRET_OR_HASHED_PASSWORD',
            'domainid' => '1',
            'responsetype' => 'json',
        )
    )
);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
curl_close($ch);

我想在没有 PHP 和 Python 的情况下使用此请求。我应该使用什么库以及如何在有效负载中设置变量?(php 或 python 样式?)

我应该使用什么库

requests 是流行的 python 模块,用于处理 HTTP(S) 请求,但请注意,它是外部模块,需要按如下方式安装

pip install requests

做起来不难,但是如果你不允许安装外部模块,你就不能使用它。在这种情况下,您可以使用 urllib.request 内置模块。

如何设置负载中的变量?

只需将您的 array 翻译成 pythondict 并将其用作 data 参数,requests Quickstart 提供以下示例

r = requests.post('https://httpbin.org/post', data={'key': 'value'})

{'key': 'value'}python 等同于 PHP7 array('key' => 'value'){'key1': 'value1', 'key2': 'value2'} 将是 array('key1' => 'value1', 'key2' => 'value2') 等等