在实现buy()
函数时,我需要使用从helpers.py
中找到的lookup(symbol)
函数返回的字典,并在app.py
中访问它。但它似乎没有返回任何数据。代码如下:
# in helper.py
"""
Decorate routes to require login.
https://flask.palletsprojects.com/en/1.1.x/patterns/viewdecorators/
"""
@wraps(f)
def decorated_function(*args, **kwargs):
if session.get("user_id") is None:
return redirect("/login")
return f(*args, **kwargs)
return decorated_function
def lookup(symbol):
"""Look up quote for symbol."""
# Contact API
try:
api_key = os.environ.get("API_KEY")
response = requests.get(f"https://cloud-sse.iexapis.com/stable/stock/{urllib.parse.quote_plus(symbol)}/quote?token={api_key}")
response.raise_for_status()
except requests.RequestException:
return None
# Parse response
try:
quote = response.json()
return {
"name": quote["companyName"],
"price": float(quote["latestPrice"]),
"symbol": quote["symbol"]
}
except (KeyError, TypeError, ValueError):
return None
, app.py中的代码是
def buy():
if request.method == "GET":
return render_template("buy.html")
else:
symbol = request.form.get("symbol")
shares = request.form.get("share_num")
result = lookup(symbol)
cash = db.execute("SELECT cash FROM users WHERE id = ?", session["user_id"])
if cash < result["price"] * request.form.get("share_num"):
return apology("insufficient balance",403)
db.execute("INSERT INTO stock(symbol,name,quantity,price) VALUES (?,?,?,?) WHERE users.id = stock.user_id AND id= ?",
result["symbol"], result["name"], request.form.get("share_num"),result["price"],session["user_id"])
db.execute("UPDATE users(cash) SET (?) WHERE users.id = stock.user_id AND id=? ",
cash - result["price"] * request.form.get("share_num"), session["user_id"])
return redirect("/")
和HTML代码是
{% block title %}
buy stock
{% endblock %}
{% block main %}
<form action="/buy" method="post">
<div class="mb-3">
<input autocomplete="off" autofocus class="form-control mx-auto w-auto" name="symbol" placeholder="symbol" type="text">
</div>
<div class="mb-3">
<input class="form-control mx-auto w-auto" name="share_num" placeholder="quantity" type="number">
</div>
<button class="btn btn-primary" type="submit">buy</button>
</form>
{% endblock %}
得到的错误是
File "/workspaces/89966944/finance/helpers.py", line 33, in decorated_function
return f(*args, **kwargs)
^^^^^^^^^^^^^^^^^^
File "/workspaces/89966944/finance/app.py", line 64, in buy
if cash < result["price"] * request.form.get("share_num"):
~~~~~~^^^^^^^^^
TypeError: 'NoneType' object is not subscriptable
错误提示您正在尝试获取None对象中的键。
在本例中,result
为None,您正在尝试执行result["price"]
,这会触发TypeError
。
注意lookup
函数可以返回None
,如果:
- API有连接问题(第一次尝试除了负责检查这个)
- API返回的响应不是字典。例如,如果你输入一个不存在的符号,就会发生这种情况。(第二次尝试除外负责此)
在调用result["price"]
之前,必须检查lookup
是否返回None
,以避免获得KeyErrors
。例如:
result = lookup(symbol)
if result is None:
# Do something if lookup returns None
确保使用浏览器调用API来检查它返回的是哪种类型的数据。