Mashape API 呼び出しをキャッシュするにはどうすればよいですか。以下のコードを取得しましたが、キャッシュを行っていないようです。Mashape は unrest を使用して 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
リクエストhttpライブラリhttp://docs.python-requests.org/en/latest/index.htmlを使用して API キーを追加できる URL でそれを行うことができました。
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
私はジャンゴ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
}
}
}