首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用Python缓存Mashape调用

用Python缓存Mashape调用
EN

Stack Overflow用户
提问于 2014-10-04 13:47:59
回答 1查看 601关注 0票数 1

如何缓存Mashape调用。我得到了下面的代码,但它似乎没有进行缓存。Mashape正在使用unirest来获得API响应。

代码语言:javascript
复制
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键。

代码语言:javascript
复制
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。

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


 }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-10-05 09:41:48

这是我的工作解决方案(请随意改进此代码)

示例用法

代码语言:javascript
复制
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
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/26193442

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档