2017-08-22 33 views
0

我已经将json从api导入到了我的视图中。它现在工作得很好,但不知何故,如果我进入网站,django会缓存api给出的值,因此不会显示最近的值。我试图使用“never_cache”和“缓存控制”,但它没有奏效。有没有我能用django或Apache做的解决方案?使用导入的json api禁用django-views中的缓存

我的观点

from __future__ import unicode_literals 
from django.shortcuts import render 
from urllib import urlopen 
import json 
from django.views.decorators.cache import never_cache, cache_control 

response = json.loads(urlopen('http://api.fixer.io/latest').read()) 
usdollar = response['rates']['USD'] 

#@never_cache 
@cache_control(max_age=0, no_cache=True, no_store=True, must_revalidate=True) 
def home(request): 
    return render(request, "index.html", {"usdollar":usdollar}) 

回答

0

此刻,你是在模块级使你的API调用。这意味着它只会在模块加载时运行一次。您应该将代码移到您的视图中:

#@never_cache 
@cache_control(max_age=0, no_cache=True, no_store=True, must_revalidate=True) 
def home(request): 
    response = json.loads(urlopen('http://api.fixer.io/latest').read()) 
    usdollar = response['rates']['USD'] 
    return render(request, "index.html", {"usdollar":usdollar}) 
+0

谢谢,现在完美的作品 – tbenji84