Django 其他dict必须是映射(类似字典)对象
我有以下上下文处理器:Django 其他dict必须是映射(类似字典)对象,django,django-templates,Django,Django Templates,我有以下上下文处理器: def btc_price(request): price = get_price() return {'btc_price', price} 如果有关系,下面是我的get_price函数: def get_price(): now = datetime.datetime.now() if PriceCache.objects.all().exists(): last_fetch = PriceCache.objects.
def btc_price(request):
price = get_price()
return {'btc_price', price}
如果有关系,下面是我的get_price函数:
def get_price():
now = datetime.datetime.now()
if PriceCache.objects.all().exists():
last_fetch = PriceCache.objects.latest('time_fetched')
time_last_fetched = last_fetch.time_fetched
day = datetime.timedelta(days=1)
if now - time_last_fetched > day:
api_url = urllib2.Request("https://www.bitstamp.net/api/ticker/")
opener = urllib2.build_opener()
f = opener.open(api_url)
fetched_json = json.loads(f.read())
cost_of_btc = fetched_json['last']
PriceCache.objects.create(price=cost_of_btc, time_fetched=now)
last_fetch.delete()
return cost_of_btc
else:
return last_fetch.price
else:
api_url = urllib2.Request("https://www.bitstamp.net/api/ticker/")
opener = urllib2.build_opener()
f = opener.open(api_url)
fetched_json = json.loads(f.read())
cost_of_btc = fetched_json['last']
PriceCache.objects.create(price=cost_of_btc, time_fetched=now)
return cost_of_btc
我在TEMPLATE_context_PROCESSORS中声明了上下文处理器,如下所示:
TEMPLATE_CONTEXT_PROCESSORS = (
"django.contrib.auth.context_processors.auth",
"django.core.context_processors.debug",
"django.core.context_processors.i18n",
"django.core.context_processors.media",
"django.core.context_processors.request",
"Computer_store.processors.btc_price",
)
在我的render\u to\u response
函数中正确定义了请求上下文
return render_to_response('home.html', {}, context_instance = RequestContext(request))
然而,当我试图在主页上运行此代码时,我得到一个奇怪的错误。
TypeError位于/
其他dict必须是映射(类似字典)对象。
可以进行完整的回溯。看起来
return {'btc_price', price}
应成为:
return {'btc_price': price}
哇!我真傻。谢谢。有人能详细解释一下这个错误消息的意思吗?