如何在Flask服务器上检查现有用户的sql数据库

时间:2019-06-13 21:10:19

标签: python flask flask-sqlalchemy

我有一个带有登录表单的Web应用程序,并且希望记录用户名。如果数据库中存在一个名称,那么我想登录他们,如果不存在,我想将新用户添加到数据库中,然后再登录。当前,它可以与新用户一起使用,但是如果已经使用了用户名失败。

from flask import Flask, flash, redirect, render_template, request, url_for
import os

from flask_sqlalchemy import SQLAlchemy

project_dir = os.path.dirname(os.path.abspath(__file__))
database_file = "sqlite:///{}".format(os.path.join(project_dir, "bookdatabase.db"))

app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = database_file

db = SQLAlchemy(app)

class MyUser(db.Model):
    title = db.Column(db.String(80), unique=True, nullable=False, primary_key=True)

    def __repr__(self):
        return "<User: {}>".format(self.title)



@app.route("/")
def index():
    return render_template("index.html")

@app.route('/login', methods = ['GET', 'POST'])
def login():
  error = None
  users = MyUser.query.all()
  if request.method == 'POST':
    x = request.form['username']
    if users:
      for user in users:
        if x == user.title:
          user1 = {"username":user.title}
          flash('You were successfully logged in')
          return render_template("mypage.html", user=user1)  
        else:
          user1 = MyUser(title=request.form.get("username"))
          db.session.add(user1)
          db.session.commit()
          return render_template("mypage.html", user=user1)
    else:
      user1 = MyUser(title="admin")
      db.session.add(user1)
      db.session.commit()
  return render_template('login.html', error = error)


if __name__ == '__main__':
    #port = int(os.environ.get('PORT', 5000))
    #app.run(host='0.0.0.0', port=port)
    app.run(debug = True)

1 个答案:

答案 0 :(得分:0)

如果返回的第一个用户记录不匹配,则循环将尝试创建一个新用户。如果用户已经存在但未返回 first 记录,则可能导致重复。相反,您可以通过filter查询来确定用户名是否存在:

matches = query.filter(MyUser.title == x)

if matches:
    # user exists
else:
    # user doesn't exist