filename regex

This commit is contained in:
Michael Grote 2023-04-13 11:46:17 +02:00
parent ea991b0a7a
commit 253bd36232

84
app.py
View file

@ -1,59 +1,55 @@
import os
import re
import uuid
from flask import Flask, request, jsonify, send_from_directory, render_template
from flask import Flask, request, jsonify, send_from_directory
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = os.environ.get('UPLOAD_FOLDER', './uploads')
app.config['MAX_CONTENT_LENGTH'] = 5 * 1024 * 1024 # 5MB
UPLOAD_DIRECTORY = os.environ.get("UPLOAD_DIRECTORY", "/uploads")
if not os.path.exists(UPLOAD_DIRECTORY):
os.makedirs(UPLOAD_DIRECTORY)
VALID_FILENAME_REGEX = r'^[a-zA-Z0-9\-_\.]+$'
UPLOAD_TOKEN = os.environ.get("UPLOAD_TOKEN")
def is_valid_filename(filename):
return bool(re.match(VALID_FILENAME_REGEX, filename))
def allowed_file(filename):
return True
@app.route('/upload', methods=['POST'])
def upload_file():
if 'file' not in request.files:
return jsonify({'error': 'No file part in the request'}), 400
@app.route("/")
def index():
file = request.files['file']
if file.filename == '':
return jsonify({'error': 'No file selected for upload'}), 400
if not is_valid_filename(file.filename):
return jsonify({'error': 'Invalid filename. Only alphanumeric characters, hyphens, underscores, and periods are allowed.'}), 400
filename = file.filename
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
return jsonify({'success': 'File {} successfully uploaded'.format(filename)})
@app.route('/download/<filename>', methods=['GET'])
def download_file(filename):
try:
return send_from_directory(app.config['UPLOAD_FOLDER'], filename)
except FileNotFoundError:
return jsonify({'error': 'File not found'}), 404
@app.route('/list', methods=['GET'])
def list_files():
files = []
for filename in os.listdir(UPLOAD_DIRECTORY):
path = os.path.join(UPLOAD_DIRECTORY, filename)
total_size = 0
for filename in os.listdir(app.config['UPLOAD_FOLDER']):
path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
if os.path.isfile(path):
files.append({"filename": filename, "size": os.path.getsize(path)})
total_size = sum(f["size"] for f in files)
return render_template("index.html", files=files, total_size=total_size, count=len(files))
size = os.path.getsize(path)
files.append({'filename': filename, 'size': size})
total_size += size
return jsonify({'files': files, 'count': len(files), 'total_size': total_size})
@app.route("/upload", methods=["POST"])
def upload():
if "file" not in request.files:
return "No file found", 400
file = request.files["file"]
if file.filename == "":
return "No file selected", 400
if not allowed_file(file.filename):
return "Invalid file type", 400
if UPLOAD_TOKEN and request.headers.get("Authorization") != f"Bearer {UPLOAD_TOKEN}":
return "Unauthorized", 401
filename = str(uuid.uuid4())
file.save(os.path.join(UPLOAD_DIRECTORY, filename))
return jsonify({"filename": filename})
if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0', port=int(os.environ.get('PORT', 5000)))
@app.route("/download/<filename>", methods=["GET"])
def download(filename):
return send_from_directory(UPLOAD_DIRECTORY, filename)
@app.route("/metrics")
def metrics():
files = []
for filename in os.listdir(UPLOAD_DIRECTORY):
path = os.path.join(UPLOAD_DIRECTORY, filename)
if os.path.isfile(path):
files.append({"filename": filename, "size": os.path.getsize(path)})
total_size = sum(f["size"] for f in files)
return jsonify({"count": len(files), "total_size": total_size, "files": files})
if __name__ == "__main__":
app.run(host="0.0.0.0", port=5040, debug=True)