【发布时间】:2020-08-07 15:44:50
【问题描述】:
我在获取 CS50 Finance 的股票报价时遇到问题,无论我输入什么股票代码,它都会返回“无效代码”的错误,而我终其一生都无法弄清楚原因。我已经包含了我的 application.py 的相关部分”
@app.route("/quote", methods=["GET", "POST"])
@login_required
def quote():
if request.method == "POST":
quote=lookup(request.form.get("symbol"))
if quote == None:
return apology ("invalid symbol", 400)
return render_template ("quoted.html", quote=quote)
else:
return render_template("quote.html")
以及我的quote.html(似乎有效)
{% extends "layout.html" %}
{% block title %}
Quote
{% endblock %}
{% block main %}
<form action="/quote" method="post">
<div class= "form-group">
<input autocomplete="off" autofocus class="form-control" name ="symbol" placeholder = "type symbol here" type="text" require/>
</div>
<button class="btn btn-primary" type="submit">Get quote</button>
</form>
{% endblock %}
还有我的quoted.html(我从来没有看到,因为我得到了道歉:
{% extends "layout.html" %}
{% block title %}
Quoted
{% endblock %}
{% block main %}
<p> Today, a share of {{ quote ["symbol"] }} will cost you {{ quote ["price"] | usd }}.</p>
{% endblock %}
任何帮助将不胜感激,在此先感谢
编辑:这是从 helpers.py 中查找的,我没有编写此代码,它是为 CS50 类提供的:
"""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()
}
【问题讨论】:
-
也许问题出在您的
lookup函数中?尝试打印request.form.get("symbol")看看是否符合您的预期。 -
显示
lookup()的代码 -
在编辑中添加了 lookup() 的代码
-
lookup函数中的 URL 不起作用。没有像download.finance.yahoo.com这样的网站。这可能是一个旧练习,并且 URL 已更改。 -
雅虎财经 API 已关闭:quora.com/Did-Yahoo-Stock-API-shut-down
标签: python html flask cs50 stock