怎么用django多吃一个休息api?

时间:2018-03-17 04:48:55

标签: python api python-requests

我想使用request.get()方法从django中的多个api获取数据。通常我们提取这样的数据:

response = requests.get('http://freegeoip.net/json/')

是否有可能从3个不同的API获取数据。

response=requests.get('http://freegeoip.net/json/','http://api.example.com','http://api.anotherexample.com');

3 个答案:

答案 0 :(得分:0)

您可以在网址上创建网址列表和迭代

<强>实施例

urlList = ['http://freegeoip.net/json/','http://api.example.com','http://api.anotherexample.com']
result = []
for url in urlList:
    result.append(requests.get(url))
print(result)

答案 1 :(得分:0)

最简单的答案是NO,因为python请求模块是泛型函数;即使您将3个网址实施到相同或不同的服务器,您也必须单独请求它,因此,如果它是3请求您必须请求三次;它不应该组合它用于错误检测的原因。您无法处理或知道哪个网址导致错误,因此您没有收到回复。

url_set = ['http://freegeoip.net/json/','http://api.example.com','http://api.anotherexample.com']
response_set = {}  # maintain dict to store responsese
for url in url_set:
    response_set[url] = request.get(url)

所以现在你可以访问各个网址的所有响应,如果你遇到任何类型的错误你可以处理它,虽然你可能面临许多不同的情况,如请求超时,SSL证书警告等。

答案 2 :(得分:0)

如果你想有点花哨并节省一些内存,请使用generator:

def get_responses(*urls, **kwargs):
    for url in urls:
        yield requests.get(url, **kwargs)

urls = ['http://freegeoip.net/json/','http://api.example.com','http://api.anotherexample.com']

for response in get_responses(*urls):
    # do something to the response