user13368804
user13368804

Reputation:

Flask: How to delete files from the server

I am trying to delete two files from my flask application. But it does not work

html

<button href="/remove/wellness" id="remove" class="btn btn-success mr-2">Remove</button>

Here is my delete function:

@app.route('/remove/<file_id>')
def remove(file_id):
    filename_jsonl = f"{file_id}.jsonl"
    filename_csv = f"{file_id}.csv"

    return os.remove(filename_jsonl, filename_csv)

Any and all help is appreciated. Thanks!

Upvotes: 0

Views: 1674

Answers (1)

arshovon
arshovon

Reputation: 13661

I solved the issue with the following directory structure:

.
├── app.py
├── templates
│   └── delete_files.html
├── wellness.csv
└── wellness.jsonl

As you can see I have two files called wellness.csv and wellness.jsonl in the directory where I have placed my app.py file. The name wellness will be passed from the template and these two files will be deleted from the directory.

app.py:

import os
from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def search():
    return render_template('delete_files.html')

@app.route('/remove/<file_id>')
def remove(file_id):
    filename_jsonl = f"{file_id}.jsonl"
    filename_csv = f"{file_id}.csv"
    try:
        os.remove(filename_jsonl)
        os.remove(filename_csv)
        return "Files are deleted successfully"
    except Exception as e:
        return f"Error in deleting files: {e}"

delete_files.html:

<html>
<head>
  <title>Delete files using button click in Flask</title>
</head>
<body>
  <a href="/remove/wellness" id="remove" class="btn btn-success mr-2">Remove</a>
</body>
</html>

Output:

After clicking the delete button I see the message Files are deleted successfully.

after successfully deletion of the files

The folder structure after deletion of the files:

.
├── app.py
└── templates
    └── delete_files.html

Update

If you want to redirect to root url after successful deletion you can use redirect method like below:

import os
from flask import Flask, render_template, redirect, url_for

app = Flask(__name__)

@app.route('/')
def search():
    return render_template('delete_files.html')

@app.route('/remove/<file_id>')
def remove(file_id):
    filename_jsonl = f"{file_id}.jsonl"
    filename_csv = f"{file_id}.csv"
    try:
        os.remove(filename_jsonl)
        os.remove(filename_csv)
        return redirect(url_for('search'))
    except Exception as e:
        return f"Error in deleting files: {e}"

Upvotes: 2

Related Questions