问题
I am trying to use a database in flask using
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
In it I am created a basic login page and a register page and when I try to use html code:
<form action="/login" method="post">
<input autocomplete="off" autofocus name="username" placeholder="Username" type="text">
<input class="form-control" name="password" placeholder="Password" type="password">
<button class="btn btn-primary" type="submit">Log In</button>
<li style="list-style-type:none;"><a href="/register">Register</a></li>
</form>
on this python flask code:
# This is the log in page
@app.route("/login", methods=["GET", "POST"])
def login():
"""Log user in"""
# Forget any user_id
session.clear()
# User reached route via POST (as by submitting a form via POST)
if request.method == "POST":
# Ensure username was submitted
if not request.form.get("username"):
return "must provide username", 403
# Ensure password was submitted
elif not request.form.get("password"):
return "must provide password", 403
# Query database for username
rows = db.execute("SELECT * FROM users WHERE username = :username",
username=request.form.get("username"))
# Ensure username exists and password is correct
if len(rows) != 1 or not check_password_hash(rows[0]["hash"], request.form.get("password")):
return "invalid username and/or password", 403
# Remember which user has logged in
session["user_id"] = rows[0]["id"]
# Redirect user to home page
return redirect("/")
# User reached route via GET (as by clicking a link or via redirect)
else:
return render_template("login.html")
I get this error:
TypeError: get_bind() got an unexpected keyword argument 'username'
I connected the database, and set up all other variables including flask_debug. I'm not sure what is wrong or how to test for it. Can anyone help me figure out why im getting this error?
回答1:
There is an error in the syntax of the postgresql query. More specifically in the sanitizing of data to avoid sql injections.
the correct syntax was
db.execute("SELECT * FROM users WHERE username = :username", {"username": request.form.get("username")})
There are also more errors in this code. For example
if len(rows) != 1:
You can not extract the len of the query. However it is possible to check for the amount of rows a query has by using the function .rowcount()
which if 0 means the search came back empty.
来源:https://stackoverflow.com/questions/61943673/typeerror-get-bind-got-an-unexpected-keyword-argument