build a flask app that allows a user to upload the file it randomizes the filename then allows the user to download the renamed file
after a file has been on the server for 2 minutes it will delete it
style the css a bit so it is a navy blue background
with a box in the middle that contains the upload and download buttons and progress bars etc
Assistant
To create a Flask app that allows a user to upload a file, randomizes the filename, and lets the user download the renamed file, you can follow the steps below. In this example, we'll use Flask, Flask-Uploads, and a simple scheduled task to delete files after 2 minutes.
Install Flask and Flask-Uploads using pip:
sh
pip install flask flask-uploads
Create a new file called app.py and add the following code:
python
import os
import random
import string
from datetime import datetime
from flask import Flask, render_template, request, send_from_directory
from flask_uploads import UploadSet, configure_uploads, DATA
app = Flask(__name__)
# Configure the file uploader
files = UploadSet('files', DATA)
app.config['UPLOADED_FILES_DEST'] = 'uploads'
configure_uploads(app, files)
# Function to generate a random string for the filename
def random_string(length=10):
letters = string.ascii_letters
return ''.join(random.choice(letters) for _ in range(length))
@app.route('/', methods=['GET', 'POST'])
def index():
if request.method == 'POST':
if 'file' in request.files:
# Uploading the file
file = request.files['file']
# Randomizing the filename and saving it
random_filename = random_string() + '.' + file.filename.split('.')[-1]
filename = files.save(file, name=random_filename)
return '<a href="/download/' + filename + '">Download ' + filename + '</a>'
return render_template('index.html')
@app.route('/download/<path:filename>', methods=['GET', 'POST'])
def download(filename):
return send_from_directory(directory=app.config['UPLOADED_FILES_DEST'], path=filename)
# Scheduler to delete files after 2 minutes
def delete_files_after_2_minutes():
now = datetime.now()
directory = app.config['UPLOADED_FILES_DEST']
for filename in os.listdir(directory):
file_path = os.path.join(directory, filename)
if os.path.isfile(file_path):
age = now - datetime.utcfromtimestamp(os.path.getctime(file_path))
if age.seconds >= 120:
os.remove(file_path)
app.before_request(delete_files_after_2_minutes)
if __name__ == '__main__':
app.run(debug=True)
Create a new file called index.html in the templates folder with the following content:
Open a browser and go to http://127.0.0.1:5000, then you can upload and download files with random filenames. The server will automatically delete files that have been on the server for more than 2 minutes.