how to avoid flask insert duplicate entries?

1.6k views Asked by At

I want to update my database using the code snipped provided below:

@app.route('/update')
def update():
    os.system('python update.py')
    return redirect(url_for('home'))

But when I use gunicorn -w 4 to run the app and click the url http://127.0.0.1:5000/update once, it will run python update.py twice. The same content be insert into the database twice.I think it may be gunicorn's multiple processing cause the problem.

I also want to make the column unique,but it will not suit my need.

How can I solve the problem? And could you tell me some good solutions to update database automatically every day.

1

There are 1 answers

1
Tometzky On BEST ANSWER

You must only change state of a system, for example make any changes to a database, on POST requests. So:

@app.route('/update',  methods=['POST'])
def update():
    os.system('python update.py')
    return redirect(url_for('home'))

Otherwise you risk double run on multiple occasions, like browser preloading, browser restart, unclosing of browser tab and many others.

I'd also use from . import update instead of os.system.