Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete files from the server with Flask

Tags:

python

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'))
like image 987
Anatoliy Fedorenko Avatar asked Oct 30 '14 07:10

Anatoliy Fedorenko


People also ask

How to delete session files in FL flask?

There are two ways on how to delete session files in Fl flask. The first method is to use the command line in editing. Simply type the command and follow it with a newline to indicate that the file should be saved. Press the return key after typing the command.

How to delete single product from database table in flask?

To delete single product from database table we can simply use WHERE condition but to delete multiple rows we need to use IN clause with WHERE condition. Even for single record deletion we can use IN clause with WHERE condition. We will create endpoint URLs for showing products details on UI (user interface) using flask template.

How to download a file in flask?

File Downloading is the process of receiving the binary or normal files from the server. Flask facilitates us to Download the files easily. Returning Various files based on the Routes 1. Importing the Libraries 2. Create Instance and Specify the File Location

How to send Python scripts using flask API?

A simple File Send Python Script using Flask API . . , app = Flask (__name__) # Specify directory to download from . . . DOWNLOAD_DIRECTORY = "<your folder directory>" """Download a file.""" Run the Application by running “python servefile.py”. Go to browser and type “ http://localhost:8000/get-files/<filename with extension> ”.


1 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:

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

like image 85
dpgaspar Avatar answered Oct 02 '22 13:10

dpgaspar