如何避免烧瓶插入重复条目?

how to avoid flask insert duplicate entries?

我想使用下面提供的代码片段更新我的数据库:

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

但是当我使用 gunicorn -w 4 到 运行 应用程序并单击 url http://127.0.0.1:5000/update 一次时,它会 运行 python update.py 两次.同样的内容被插入数据库twice.I认为可能是gunicorn的多重处理导致的问题

我也想使该列唯一,但它不适合我的需要。

我该如何解决这个问题? 能不能告诉我一些每天自动更新数据库的好办法。

您只能根据 POST 请求更改系统状态,例如对数据库进行任何更改。所以:

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

否则,您会在多种情况下面临双倍 运行 的风险,例如浏览器预加载、浏览器重启、浏览器选项卡的关闭等等。

我也会使用 from . import update 而不是 os.system