【发布时间】: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 的答案是正确的。