Flask SQAlchemy + SQLite NOT NULL失败

时间:2017-03-20 20:49:15

标签: python sqlite flask flask-sqlalchemy

我有一个简单的注册表单,它将插入到我的SQLite DB中。但它失败了,显示email列与NOT NULL约束相矛盾。即使来自email的输入正在提交和识别。

数据库模型(Flask SQLAlchemy):

class Registration(db.Model):
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    email = db.Column(db.String(50))
    username = db.Column(db.String(20))
    password = db.Column(db.String(350))

注册码

form = RegistrationForm()
    if request.method == "POST" and form.validate_on_submit():
        username = form.username.data
        email = form.email.data
        password = bcrypt.hashpw(form.password.data.encode('utf-8'), bcrypt.gensalt(14))

        # Query DB for existing username
        user = Registration.query.filter_by(username=username).first()
        # Query DB for existing email
        email = Registration.query.filter_by(email=email).first()

        # If username exits
        if user:
            flash("Sorry that username is already taken, please choose another!")
            return render_template('register.html', form=form)

        # If email exists
        elif email:
            flash('That email is already associated with another account, please use another!')
            return render_template('register.html', form=form)

        else:
            new_user = Registration(email=email, username=username, password=password)
            db.session.add(new_user)
            db.session.commit()
            flash("Thanks for registering, {u}!".format(u=username))

            return redirect(url_for('home'))

错误:

(sqlite3.IntegrityError) NOT NULL constraint failed: registration.email [SQL: 'INSERT INTO registration (email, username, password) VALUES (?, ?, ?)'] [parameters: (None, 'test_user', b'$2b$14$fiL14w35s.kckAY5timb9uE0d9pQ/K9RZpRuNPBlnsKl3FHaQfFoG')]

但它显示找到了电子邮件地址:

2017-03-20 13:35:19,082 INFO sqlalchemy.engine.base.Engine ('insert@gmail.com', 1, 0)

然后显示后的2行:

2017-03-20 13:35:19,084 INFO sqlalchemy.engine.base.Engine INSERT INTO registration (email, username, password) VALUES (?, ?, ?)
2017-03-20 13:35:19,084 INFO sqlalchemy.engine.base.Engine (None, 'test_user', b'$2b$14$fiL14w35s.kckAY5timb9uE0d9pQ/K9RZpRuNPBlnsKl3FHaQfFoG')

为什么会尝试为None插入email,即使它显示实际发送的电子邮件?

1 个答案:

答案 0 :(得分:0)

因为您运行此查询:

email = Registration.query.filter_by(email=email).first()

您正在使用该查询的结果覆盖email变量。如果找不到匹配的条目,您将email替换为None,这会导致您的问题。

另外有趣的是,我实际上无法理解您的email列有NOT NULL约束的原因 - 您对该列的定义是:

email = db.Column(db.String(50))

没有为列指定任何约束。如果要确保此列永远不为NULL,则应将其更改为:

email = db.Column(db.String(50), nullable=False)