gpt4 book ai didi

python - 如何使用 Flask 从服务器删除文件

转载 作者:行者123 更新时间:2023-11-28 20:21:44 25 4
gpt4 key购买 nike

当我用这个函数上传文件时:

@app.route('/add_item', methods=['GET', 'POST'])
@login_required
def new_item():
error = None
form = AddItemForm(request.form)
if request.method == 'POST':
file = request.files['file']
if file and allowed_file(file.filename) and form.name.data != "" and form.description.data != "":
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOADED_ITEMS_DEST'], filename))
new_item = Item(
filename,
form.name.data,
form.description.data,
form.price.data,
form.age.data,
form.particles.data,
form.category.data,
'1',
)
db.session.add(new_item)
db.session.commit()
return redirect(url_for('admin_items'))
else:
return render_template('admin_items.html', form=form, error=error)
if request.method == 'GET':
return redirect(url_for('admin_items'))

如何使用删除项目的功能删除这个上传的文件?问题是我目前的功能只删除项目的内容(描述、价格等),但上传到文件夹的实际文件当然不会删除!这就产生了问题!

这是我的删除函数:

# Delete Items:
@app.route('/delete_item/<int:item_id>/', methods=['GET', 'POST'])
@login_required
def delete_item(item_id):
new_id = item_id
os.remove(os.path.join(app.config['UPLOADED_ITEMS_DEST'], filename))
db.session.query(Item).filter_by(item_id=new_id).delete()
db.session.commit()

return redirect(url_for('admin_items'))

最佳答案

@app.route('/delete_item/<int:item_id>/', methods=['GET', 'POST'])
@login_required
def delete_item(item_id):
new_id = item_id
item = self.session.query(Item).get(item_id)
os.remove(os.path.join(app.config['UPLOADED_ITEMS_DEST'], item.filename))
self.session.delete(item)
db.session.commit()
return redirect(url_for('admin_items'))

当然,您应该实现适当的错误捕获。看看:

https://github.com/dpgaspar/Flask-AppBuilder/blob/master/flask_appbuilder/models/sqla/interface.py#L366

关于python - 如何使用 Flask 从服务器删除文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26647248/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com