繁体   English   中英

PHP Curl与Python请求

[英]PHP Curl vs Python Requests

我目前正在编写一段代码来与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.")

将BASE_URL更改为:

'https://website.api.com'

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

尝试使用postman调试API。

事实证明,我的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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM