我有一个python函数: -
def lookup(symbol):
"""Look up quote for symbol."""
# reject symbol if it starts with caret
if symbol.startswith("^"):
return None
# reject symbol if it contains comma
if "," in symbol:
return None
# query Yahoo for quote
# http://stackoverflow.com/a/21351911
try:
url = "http://download.finance.yahoo.com/d/quotes.csv?f=snl1&s={}".format(symbol)
webpage = urllib.request.urlopen(url)
datareader = csv.reader(webpage.read().decode("utf-8").splitlines())
row = next(datareader)
except:
return None
# ensure stock exists
try:
price = float(row[2])
except:
return None
# return stock's name (as a str), price (as a float), and (uppercased) symbol (as a str)
return {
"name": row[1],
"price": price,
"symbol": row[0].upper()
}
然后我将它导入我的Jinja模板: -
app.jinja_env.globals.update(lookup = lookup)
在普通的python文件中,这个: -
print(lookup("NFLX"))
产生输出: -
{'price': 162.43, 'symbol': 'NFLX', 'name': 'Netflix, Inc.'}
但在我的模板中,这个: -
{% set stock = lookup[info['stock']] %}
{{stock['price']}}
给出错误: -
jinja2.exceptions.UndefinedError: 'function object' has no attribute 'AAPL'
AAPL是info ['stock']的值,是Apple的股票名称。我在普通的python文件中运行相同的代码,然后运行,我还尝试运行另一个在Jinja中返回usd数值的函数,并且它运行(可能因为它只是返回一个值)。为什么查找功能在模板中不起作用?
答案 0 :(得分:1)
一个简单的语法修复:
{% set stock = lookup( info['stock'] ) %} # round brackets for function calls
else:您正在尝试在“查找”中访问value
“AAPL”key
作为dict
,这是一个函数对象,而不是字典