PHP Curl与Python请求

时间:2018-01-23 10:20:39

标签: php python curl 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.")

2 个答案:

答案 0 :(得分:0)

将BASE_URL更改为:

是理想的选择
'https://website.api.com'

与php相比,代码看起来很好,并且应该正常工作。(难道你不应该像令牌一样传递某种身份验证吗?)。

尝试使用postman调试您的API。

答案 1 :(得分:0)

事实证明我的API只会接受在标头中传输的cookie,因此我写了一个轻微的hack,将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)