有没有办法使用 python flask 来接收来自用户的唯一输入

Is there a way to use python flask to receive a unique input from the user

我从去年开始为我的正常运行的网站创建了一个数据库,我忘记将我的模型的输入设置为唯一。它允许对同一条记录进行多次输入,无论如何我可以在我的路线中改变它吗?我使用 python flask 和 mysqlite 作为数据库

@app.route("/",  methods=['POST', 'GET'])
def create_numbers():
    if request.method =="GET":
        return render_template('index.html')
    else:
        title = request.form["name"]
        phone = request.form["phone"]

        validated = False
        if title == '' or phone == '':
            flash("All fields are required")
        else:
            validated = True
        if not validated:
            return render_template("index.html")
        watch = Watch(name=title ,phone=phone)
        db.session.add(watch)
        db.session.commit()
        return redirect(url_for("userindexes"))

你有两个选择。您可以先编辑 Watch 数据库模型并使某些列在数据库层中唯一。这将防止添加违反此规则的条目。

如果您需要多个唯一列,请使用 SQLAlchemy 的 UniqueConstraint 功能。

class Watch(Model):
    #... other elements
    name = Column(db.String(80), unique=True, nullable=False)

这种方法的缺点是尝试添加重复条目会引发异常,您现在必须捕获并处理该异常,否则如果用户输入重复输入,您将向用户发送 500 HTTP 响应。

另一种方法是简单地在你的 flask 路由中做一个查询,在添加新的数据库条目之前检查重复项。

@app.route("/",  methods=['POST', 'GET'])
def create_numbers():
    if request.method =="GET":
        return render_template('index.html')
    else:
        title = request.form["name"]
        phone = request.form["phone"]

        duplicate = Watch.query.filter(
            (Watch.name == title) &
            (Watch.phone == phone)
        ).first()

        if duplicate:
            return 'That entry is already in the database.'

        validated = False
        if title == '' or phone == '':
            flash("All fields are required")
        else:
            validated = True
        if not validated:
            return render_template("index.html")
        watch = Watch(name=title ,phone=phone)
        db.session.add(watch)
        db.session.commit()
        return redirect(url_for("userindexes"))