如何从python访问数据库行?

时间:2019-05-02 00:35:55

标签: python sqlite flask

Noob,试图弄清楚如何从我的application.py文件中访问我的sqlite数据库中的条目。简而言之,我试图向数据库中添加一个新用户和哈希密码,然后保持该用户的登录状态。我正在使用来自给定登录功能(CS50 Finance项目)的许多相同代码,但是收到“列表索引超出范围”错误,表示我无法正确访问该行。简单的答案(我能理解的)比我无法理解的复杂答案更受欢迎。

我在这里和互联网上进行搜索都没有成功。

@app.route("/register", methods=["GET", "POST"])
def register():
    # Forget any user_id
    session.clear()

    # User reached route via POST (as by submitting a form via POST)
    if request.method == "POST":

        # Query database for username (it should not be there if new user)
        rows = db.execute("SELECT * FROM users WHERE username = :username",
        username=request.form.get("username"))
        hash = generate_password_hash(request.form.get("password"))

        if len(rows) != 0:
            return apology("Username is already in use, please choose a unique username", 403)
        else:
            db.execute("INSERT INTO users (username, hash) VALUES(:username, :hash)", username=request.form.get("username"), hash=hash)

        # Problem is with the below line (copied from Login function): 
        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("register.html")

1 个答案:

答案 0 :(得分:0)

原来,我忘记了再次查询我的sql数据库,因此正确的代码如下:

@app.route("/register", methods=["GET", "POST"])
def register():

    # Forget any other user_id
    session.clear()

    # User reached route via POST (as by submitting a form via POST)
    if request.method == "POST":
        # Query database to see if it already contains the username, with username being posted from HTML page
        rows = db.execute("SELECT * FROM users WHERE username = :username", username=request.form.get("username"))
        hash = generate_password_hash(request.form.get("password"))

        # Case where username already exists in database
        if len(rows) != 0:
            return apology("Username is already in use, please choose a unique username", 403)
        # Else insert name into database
        else:
            db.execute("INSERT INTO users (username, hash) VALUES(:username, :hash)", username=request.form.get("username"), hash=hash)

        # Now pull that user from the database
        rows = db.execute("SELECT * FROM users WHERE username = :username", username=request.form.get("username"))

        # Remember which user has logged in
        session["user_id"] = rows[0]["id"]

        # Redirect user to home page
        return redirect("/")