我的代码似乎一切正常,但是运行/buy
时遇到check50
的一个错误。 :(买入处理小数,负数和非数字份额。预期状态码为400,但得到200。
我认为check50
在甚至可以提交购买表格之前检查1.5
或字符串之类的非整数时,正在接收状态代码200。
Flask应用程序:
@app.route("/buy", methods=["GET", "POST"])
@login_required
def buy():
"""Buy shares of stock"""
rows = db.execute("SELECT * FROM users WHERE id = :id", id=session["user_id"])
if request.method == "POST":
ticket = lookup(request.form.get("symbol"))
if not ticket:
return apology("Stock symbol not correct!")
cash = rows[0]["cash"]
if "." in request.form.get("shares") or "/" in request.form.get("shares") or "," in request.form.get("shares"):
return apology("Number of shares must be a positive integer!")
try:
shares = float(request.form.get("shares"))
except:
return apology("Number of shares must be a positive integer!")
if (ticket["price"] * shares) > cash:
return apology("Sorry you don't have sufficient amount of cash!")
transaction = db.execute("INSERT INTO transactions (username, company, symbol, shares, transaction_type, transaction_price) VALUES (:username, :company, :symbol, :share, :transaction_type, :transaction_price)",
username=rows[0]["username"], company=ticket["name"], symbol=ticket["symbol"], share=shares, transaction_type="buy", transaction_price=ticket["price"] * shares)
if not transaction:
return apology("Error while making the transaction!")
else:
db.execute("UPDATE users SET cash = :new WHERE id = :id", new=cash - ticket["price"] * shares, id=session["user_id"])
return index()
else:
return render_template("buy.html", balance=usd(rows[0]["cash"]), check=True)`
def apology(message, code=400):
"""Render message as an apology to user."""
def escape(s):
"""
Escape special characters.
https://github.com/jacebrowning/memegen#special-characters
"""
for old, new in [("-", "--"), (" ", "-"), ("_", "__"), ("?", "~q"),
("%", "~p"), ("#", "~h"), ("/", "~s"), ("\"", "''")]:
s = s.replace(old, new)
return s
return render_template("apology.html", top=code, bottom=escape(message)), code`
HTML代码
{% extends "layout.html" %}
{% block title %}
Buy
{% endblock %}
{% block main %}
<table class="table">
<thead>
<tr>
<th>Your available balance</th>
</tr>
</thead>
<tbody>
<tr>
<th>{{ balance }}</th>
</tr>
</tbody>
</table>
<form action="/buy" method="post">
<div class="form-group">
<input autocomplete="off" autofocus class="form-control" name="symbol" placeholder="Symbol of stock" type="text">
</div>
<div class="form-group">
<input autocomplete="off" autofocus class="form-control" name="shares" type="number" min="1" required />
</div>
<button class="btn btn-primary" type="submit">Buy</button>
</form>
{% endblock %}
如果shares
是非整数,则应该通过apology.html
函数使用返回代码400呈现模板apology
。相反,check50
正在检测返回代码200。
还有其他人有这个问题吗?我该怎么解决?
答案 0 :(得分:1)
我能够解决问题。问题在于python代码没有检查负数,因此接受了负数(不应)。