How to Delete Files from the Server with Flask

When i upload files with this function:

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

How can i delete this uploaded file with the function which deletes the item? The issue is that the function i currently have only deletes the content of the item (description, price, etc) but the actual file which was uploaded to the folder is not removed of course! This creates a problem!

Here is my delete function:

# 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'))
2

2 Answers

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

Of course you should implement proper error catching. take a look at:

2

you can run command in Python

os.system('rm THE_FILE_TO_DELETE')

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Alexander Ross

Alexander Ross

Gaming, Esports & Interactive Media Writer

Alexander Ross has covered the video game industry for a decade, writing deep dives on game design, esports tournaments, VR developments, and gaming culture.

Share this article
Twitter Facebook Pinterest