我需要用 Python 重写这一小段代码。
该代码向指定的 URL 发出 POST 请求。在此请求中,您必须传递您的 API key 。所有响应都将采用 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 key 无效,但我知道它是正确的
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.'”
最佳答案
尝试这个的一种方法是
query = {'api_key': 'my_api_key', 'team_abbrv': 'BOS'}
r = requests.post(url_1, data=query)
关于php - 将PHP代码重写为Python(POST请求),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33989665/