【问题标题】:rewrite PHP code into Python (POST request)将 PHP 代码重写为 Python(POST 请求)
【发布时间】:2015-11-30 00:06:41
【问题描述】:

我需要用 Python 重写这小段代码。

代码向指定的 URL 发出 POST 请求。在此请求中,您必须传递您的 API 密钥。所有响应都将采用 JSON 格式。

<?php

$url = 'https://probasketballapi.com/teams';

$api_key = '__YOUR__API__KEY__';

$query_string = 'api_key=' . $api_key . '&team_abbrv=BOS';

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POSTFIELDS, $query_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

$result = curl_exec($ch);

curl_close($ch);

echo $result;

?>

这是我目前的代码,响应是无效的 api 密钥,但我知道它是正确的

import urllib, urllib2, json, requests

url_1='http://api.probasketballapi.com/team'
api_key='fakeAPIkey'

query_string = 'api_key='+ api_key + '&team_abbrv=BOS'
query_string2={'query_string': query_string}

r = requests.post(url_1, data=query_string2)

当我打印 r.text 时,我得到“u'Invalid API key.'”

【问题讨论】:

  • 需要用 Python 重写这小段代码。”到目前为止,你得到了什么?
  • 为什么要将查询字符串转换为 json 字符串? json 字符串不是正确的 POST 数据。
  • @furas 我不确定我是否在线关注示例代码
  • @DavidVilla 我认为 YashMehrotra 的答案是正确的。

标签: php python json post


【解决方案1】:

尝试这种方法的一种方法是

query = {'api_key': 'my_api_key', 'team_abbrv': 'BOS'}
r = requests.post(url_1, data=query)

【讨论】:

    【解决方案2】:

    来自维基百科:

    包含查询字符串的典型 URL 如下:

    http://example.com/over/there?name=ferret

    我想你只是忘记了第一个?

    所以你的网址应该被格式化为 query_string = '?api_key='+ api_key + '&amp;team_abbrv=BOS'

    第一个查询参数前面有问号

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-06
      • 1970-01-01
      相关资源
      最近更新 更多