【问题标题】:PHP Curl vs Python RequestsPHP Curl 与 Python 请求
【发布时间】:2018-01-23 10:20:38
【问题描述】:

我目前正在编写一段代码来与 Python 中的 API 交互。托管 API 的公司提供了一个 PHP 脚本,该脚本在给定正确的用户名和密码的情况下登录 API,检索当前事件 ID(JSON 格式),然后注销。这非常有效。

目前,我正在用 Python 编写一个脚本来做同样的事情,当前代码如下所示。它成功登录和注销,但是,当它尝试检索当前事件 ID 时,我得到状态代码 404,表明该 URL 不存在,尽管这个相同的 URL 与 PHP 代码一起使用。

PHP 代码:

define('BASE_URL', 'https://website.api.com/');
define('API_USER', 'username');
define('API_PASS', 'password');

$cookiefile = tempnam(__DIR__, "cookies");
$ch = curl_init();
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookiefile);
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookiefile);

$loginParams = array(
  'username' => API_USER,
  'password' => API_PASS
);
$obj = CurlPost($ch, BASE_URL . '/api/login', $loginParams);
  if( $obj->success )
{
  echo 'API login successful.' . PHP_EOL;
}

$obj = CurlGet($ch, BASE_URL . '/api/current-event-id');
echo 'API current event ID: ' . $obj->currentEventId . PHP_EOL;

// logout of the API
$obj = CurlGet($ch, BASE_URL . '/api/logout' );
if( $obj->success )
{
  echo 'Logged out successfully.' . PHP_EOL;
}

curl_close($ch);

exit(0);

// -------------------------------------------------------------------------

// Functions
// -------------------------------------------------------------------------

// Run cURL post and decode the returned JSON object.
function CurlPost($ch, $url, $params)
{
  $query = http_build_query($params);

  curl_setopt($ch, CURLOPT_URL, $url);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_POST, count($query));
  curl_setopt($ch, CURLOPT_POSTFIELDS, $query);    

  $output=curl_exec($ch);

  $obj = json_decode($output);

  return $obj;
}

// Run cURL get and decode the returned JSON object.
function CurlGet($ch, $url)
{
  curl_setopt($ch, CURLOPT_URL, $url);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_POST, false);
  curl_setopt($ch, CURLOPT_POSTFIELDS, '');

  $output=curl_exec($ch);
  $obj = json_decode($output);
  return $obj;
}

Python 代码:

import requests

BASE_URL = 'https://website.api.com/';
API_USER = "username";
API_PASS = "password";
headers = {'content-type': 'application/json'}

PARAMS = {'username':API_USER,'password':API_PASS}
session = requests.Session()

# Login
resp = session.post(BASE_URL + '/api/login',data=PARAMS)
if resp.status_code != 200:
    print("*** ERROR ***: Login failed.")
else:
    print("API login successful.")

resp = session.get(BASE_URL + '/api/current-event-id', headers=headers)
print(resp.status_code)
print(resp.text)
# Logout
resp = session.get(BASE_URL + '/api/logout')
if resp.status_code != 200:
    print("*** ERROR ***: Logout failed.")
else:
    print("API logout successful.")

【问题讨论】:

    标签: php python curl python-requests


    【解决方案1】:

    最好将 BASE_URL 更改为:

    'https://website.api.com'
    

    与 php 相比,该代码对我来说看起来不错,并且应该可以正常工作。(您不应该通过某种身份验证,例如令牌吗?)。

    尝试使用 postman 调试您的 API。

    【讨论】:

    • 谢谢,我去看看邮递员。至于身份验证,这是由登录时创建的会话 cookie 处理的。在 PHP 代码中,这是由“CURLOPT_COOKIEJAR”处理的,据我所知,Python“requests.Session()”应该做类似的事情。
    • 这应该是评论,而不是答案。
    【解决方案2】:

    事实证明,我的 API 只接受在标头中传输的 cookie,因此我编写了一个小技巧,将 cookiejar 转储为可以在标头文件中发送的字符串。

    cookies = json.dumps(requests.utils.dict_from_cookiejar(resp.cookies));
    cookies = cookies.replace('"', '')
    cookies = cookies.replace('{', '')
    cookies = cookies.replace('}', '')
    cookies = cookies.replace(': ', '=')
    cookies = cookies.replace(',', ';')
    
    headers = {'Cookie':cookies}
    resp = session.get(BASE_URL + '/api/current-event-id', headers=headers)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-01-11
      • 2013-12-13
      • 1970-01-01
      • 1970-01-01
      • 2012-11-05
      • 2011-03-07
      • 1970-01-01
      相关资源
      最近更新 更多