Кажется, что все работает нормально с моим кодом, однако я сталкиваюсь с единственной ошибкой для /buy
при запуске check50
. :( покупка обрабатывает дробные, отрицательные и нечисловые акции. ожидаемый код состояния 400, но получил 200.
Я думаю, check50
получает код состояния 200 при проверке нецелого числа, такого как 1.5
или строки, еще до того, как форму покупки можно будет отправить.
Приложение для колб:
@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
с помощью функции apology
с кодом возврата 400. Вместо этого check50
обнаруживает код возврата 200.
У кого-нибудь еще есть эта проблема? Как я могу решить это?