【问题标题】:Invalid Symbol for CS50 finance, even when I use the correct symbolCS50 金融的符号无效,即使我使用了正确的符号
【发布时间】: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


【解决方案1】:

好的,所以我想发布一个正式的答案,但我必须感谢学分中的你们。 GAEfan 为我指出了正确的方向,即问题可能出在我的 lookup() 中。然后 Barmar 指出用于我的 lookup() 的网站不再使用。我不知道发生了什么,但我从官方 CS50 链接下载了分发代码,也许我遇到了故障或下载时出错,但重新下载分发代码,让我获得了最新版本以供查找() 功能。不打算回答我自己的问题,但想结束这个问题并感谢大家帮助我。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-11-15
    • 1970-01-01
    • 2017-02-06
    • 1970-01-01
    • 2022-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多