2014-10-04 52 views
1

如何緩存Mashape API調用。我得到了下面的代碼,但它似乎沒有做緩存。 Mashape正在使用unirest來獲取API響應。在Python中緩存Mashape API調用

def fetchMashape(url, headers): 
    cached = unirest.get(url, headers=headers) #cache.get(url) 
    content ="" 
    if not cached: 
     response = unirest.get(url, 
        headers=headers) 
    else: 
     response = cached 
    dictionary = json.loads(response.raw_body) 

    return dictionary 

我能夠用一個URL來做到這一點,我可以使用請求HTTP庫http://docs.python-requests.org/en/latest/index.html例如追加API密鑰

from django.core.cache import cache 
from urllib2 import Request, urlopen, build_opener 
from urllib import urlencode 
import json, ast 
import unirest 
import requests 
import xmltodict 

test = fetchJson("http//www.myapi.com/v1/MY_API_KEY/query/json=blahblah") 

#fetchJson with caching 
def fetchJson(url): 
    cached = cache.get(url) 
    content = "" 
    if not cached: 
     r = requests.get(url) 
     if(r.ok): 
      cache.set(url, r.text) 
      content = r.text 
     else: 
      content = None 
    else: 
     # Return the cached content 
     content = cached 
    if content is not None: 
     return json.loads(content) 
    else: 
     return None 

我使用的是django 1.6.6。緩存存儲在數據庫中。我的settings.py文件。數據庫的名稱是dev_cache。

CACHES = { 
     'default': { 
      'BACKEND': 'django.core.cache.backends.db.DatabaseCache', 
      'LOCATION': 'dev_cache', 
      'TIMEOUT': 60*60*24*7*4, 
      'VERSION': 1, 
      'OPTIONS': { 
       'MAX_ENTRIES': 1022000 
      } 


} 
} 
+1

嗨cloudviz,希望我可以幫你,但請你能告訴我多一點在下面: *您是否安裝了Unirest庫?我在代碼中看不到它 *緩存是指將API響應保存到變量中嗎?請記住,如果您運行腳本兩次,在第一個腳本運行後變量將不再存在,也許您最好將它寫入磁盤上的某個數據庫或靜態文件,以便進行緩存? – 2014-10-04 14:08:07

+0

謝謝。我更新了我的問題@API_sheriff_orlie。我已經安裝了Unirest庫。緩存 - 我想將響應的內容(例如JSON)存儲到名爲dev_cache的數據庫中。這一切工作正常,它是mashape api響應的緩存,無法正常工作。 – cloudviz 2014-10-04 15:01:01

+0

您是否嘗試在if範圍之外定義「響應」變量? – 2014-10-04 18:36:55

回答

1

這是我工作的解決方案(隨意提高該代碼)

用法示例

url = "https://something_api.p.mashape.com/q=whateverquery", 
headers={"X-Mashape-Key": "ABCDEFG12345"} 
test = fetchMashape(url, headers) 

def fetchMashape(url, headers): 
    cached = cache.get(url) 
    content = "" 
    if not cached: 
     response = unirest.get(url, 
       headers=headers) 
     print "not cached" 
     if response is not None: 
      cache.set(url, response.raw_body) 
      content = response.raw_body 
     else: 
      content = None 
    else: 
     content = cached 
     print "already cached" 

    dictionary = json.loads(content) 

    return dictionary