2017-04-22 23 views
0

所以標題是有點混亂我想..如何使從單一的URL多​​頁多個API調用

我有我一直在寫,這將顯示一些隨機數據的腳本和其他非要點,當我打開我的外殼。由於我使用了多個網址,因此我使用了grequests來進行API調用。對於我的天氣數據,我使用WeatherUnderground的API,因爲它會提供主動警報。 警報條件數據位於不同的頁面上。我無法弄清楚的是如何在正在發出請求時在grequests對象中插入適當的名稱。下面是我的代碼:

URLS = ['http://api.wunderground.com/api/'+api_id+'/conditions/q/autoip.json', 
     'http://www.ourmanna.com/verses/api/get/?format=json', 
     'http://quotes.rest/qod.json', 
     'http://httpbin.org/ip'] 

requests = (grequests.get(url) for url in URLS) 
responses = grequests.map(requests) 
data = [response.json() for response in responses] 

#json parsing from here 

在URL 'http://api.wunderground.com/api/'+api_id+'/conditions/q/autoip.json'我需要的API請求條件警報找回我需要的數據。如何在不重寫第四個URLS字符串的情況下執行此操作?

我已經試過

pages = ['conditions', 'alerts'] 
URL = ['http://api.wunderground.com/api/'+api_id+([p for p in pages])/q/autoip.json'] 

但是,我敢肯定,你們中的一些更豐富的程序員都知道,拋出和異常。那麼我怎麼能遍歷這些頁面,或者我必須寫出完整的URL?

謝謝!

回答

0

好吧我實際上能夠弄清楚如何通過使用簡單的for循環來調用grequests對象中的每個單獨的頁面。這裏是我用來產生預期結果的代碼:

import grequests 

pages = ['conditions', 'alerts'] 
api_id = 'myapikeyhere' 

for p in pages: 
    URLS = ['http://api.wunderground.com/api/'+api_id+'/'+p+'/q/autoip.json', 
      'http://www.ourmanna.com/verses/api/get/?format=json', 
      'http://quotes.rest/qod.json', 
      'http://httpbin.org/ip'] 

    #create grequest object and retrieve results 
    requests = (grequests.get(url) for url in URLS) 
    responses = grequests.map(requests) 
    data = [response.json() for response in responses] 

    #json parsing from here 

我還不確定爲什麼我以前無法弄清楚。

grequests庫的文檔here