Sha*_*Sid 2 session flask python-3.x flask-sqlalchemy
在我的Signedup路线中,我试图将用户 ID 存储在会话中并自动登录用户,但是当我尝试这样做时,我收到此错误:
TypeError: object of type 'ResultProxy' does not support indexing
而且,在我的signin路线中,我试图记住哪个用户已登录,但在这里出现错误:
TypeError: object of type 'ResultProxy' has no len()
signedup 路线 application.py
@app.route("/signedup",methods=["GET","POST"])
def signedup():
if request.method=="POST":
password = request.form.get("password")
hash = pwd_context.encrypt(password)
name = request.form.get("name")
if not name:
return "must provide username"
elif not password:
return "must provide password"
registration = db.execute("INSERT INTO users (username,password) VALUES (:username,:password)",
{"username":name,"password":hash})
if not registration:
return "pick a different username"
# Store their ID in session and log them in automatically
user_id = db.execute("SELECT user_id FROM users where username = :username",{"username":name})
# It means something like - "give me the first row in result
# and retrieve the value of the key "id"
#ERROR
session["user_id"] = user_id[0]["id"]
db.commit()
return render_template("success.html",name = name)
else:
return render_template("signup.html")
Run Code Online (Sandbox Code Playgroud)
signin 路线 application.py
@app.route("/signin",methods=["GET","POST"])
def signin():
# LOG A USER IN
#forget any user_id
session.clear()
if request.method == "GET":
return render_template("login.html")
else:
user_name = request.form.get("username")
# ensure username is provided
if not request.form.get("username"):
return "must provide username"
# ensure password is provided
elif not request.form.get("password"):
return "must provide password"
# query the database for the username
rows = db.execute("SELECT * FROM users where username = :username",{"username":user_name})
# ensure username exists
if len(rows) != 1 or not pwd_context.verify(request.form.get("password"),rows[0]["hash"]):
return "Invalid username"
# remember which user has logged in
session["user_id"] = rows[0]["id"]
Run Code Online (Sandbox Code Playgroud)
我有同样的错误并通过在 db.execute 命令的末尾添加 .fetchone() 来解决:
user_id = db.execute("SELECT user_id FROM users where username = :username",{"username":name}).fetchone()
Run Code Online (Sandbox Code Playgroud)
您必须使用 .fetchone (返回单个结果)或 .fetchall (返回所有结果)才能使用 SQLAlchemy 命令返回的 resultProxy 对象的索引。
| 归档时间: |
|
| 查看次数: |
2632 次 |
| 最近记录: |