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

Time:02-06

I create a database for my functioning website since last year, I forgot to set the input for my model as unique. it allows multiple entry for the same record is there anyway i can change this in my route? I use python flask and mysqlite as the database

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

CodePudding user response:

You have two options. You can first edit the Watch database model and make certain columns unique in the database layer. This will prevent entries being added that violate this rule.

If you need to have multiple unique columns, use the UniqueConstraint feature of SQLAlchemy.

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

The downside to this approach is that attempts to add duplicate entries will raise an Exception that you will now have to catch and handle otherwise you will send a 500 HTTP response back to the user if they enter duplicate input.

The other approach is to simply do a query in your flask route that checks for duplicates before adding the new database entry.

@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"))
  •  Tags:  
  • Related