登录Flask Alchemy vs sqlite3

时间:2019-08-12 21:07:58

标签: python sqlite sqlalchemy flask-sqlalchemy

我一直在开发带有sqlite3数据库的flask应用程序。现在要将其在线发布,我将数据库从sqlite3切换到Sqlalchemy,我非常迷失。我实现了登录和注册,但是登录有问题。我必须检查输入的用户名是否确实已注册,并且密码是否与数据库中的密码匹配

我已经创建了表格:

class Usuarios(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True, nullable=False)
    hash = db.Column(db.String(120), unique=True, nullable=False)
    provincia = db.Column(db.String(80))
    mail = db.Column(db.String(80), nullable=False)
    def __init__(self, username, hash, provincia, mail):
        self.username = username
        self.hash = hash
        self.provincia = provincia
        self.mail = mail

这是我的代码:

@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":
        username=request.form.get("username").upper()

        # Ensure username was submitted
        if not request.form.get("username"):
            return apology("Debe ingresar un nombre de usuario.", 403)

        # Ensure password was submitted
        elif not request.form.get("password"):
            return apology("Debe ingresar una contraseña.", 403)

        # Query database for username

        rowpass = db.session.query.filter_by(Usuarios.username = username).all()
        rows = Usuarios.query.filter_by(username=username).first()

        # Ensure username exists and password is correct
        if rows is None or not check_password_hash(rows[0]["hash"], request.form.get("password")):
            return apology("Usuario o contraseña incorrectos", 403)

        # Remember which user has logged in
        session["user_id"] = rowpass[0]["username"]

        # 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")

在sqlite3中,此代码可以完美运行,但现在我不知道如何将其正确转换为sqlalchemy:

rows = db.execute("SELECT * FROM usuarios WHERE username = :username",
                         username=request.form.get("username").upper())
if len(rows) != 1 or not check_password_hash(rows[0]["hash"], request.form.get("password")):
    return apology("Usuario o contraseña incorrectos", 403)

我认为问题出在密码检查中,我在其中保留了sqlite3的方括号[],但不确定在炼金术中是否使用过它们。 如果那是错误,我不确定那行说:

session["user_id"] = rows[0]["username"] is correct too

你怎么看?

0 个答案:

没有答案