This repository has been archived on 2024-11-06. You can view files and clone it, but cannot push or open issues or pull requests.
python-api-server/app.py
2023-04-13 11:29:47 +02:00

95 lines
2.7 KiB
Python

import os
from flask import Flask, request, redirect, url_for, send_from_directory, abort
from werkzeug.utils import secure_filename
UPLOAD_FOLDER = os.environ.get('UPLOAD_FOLDER', '/app/uploads')
ALLOWED_EXTENSIONS = {'txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'}
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
def allowed_file(filename):
return '.' in filename and \
filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
@app.route('/')
def index():
file_list = os.listdir(app.config['UPLOAD_FOLDER'])
return """
<!doctype html>
<html lang=en>
<head>
<meta charset=utf-8>
<title>File List</title>
</head>
<body>
<h1>File List</h1>
<ul>
%s
</ul>
</body>
</html>
""" % ''.join(f'<li><a href="/download/{filename}">{filename}</a></li>' for filename in file_list)
@app.route('/upload', methods=['POST'])
def upload_file():
# check if the post request has the file part
if 'file' not in request.files:
return redirect(request.url)
file = request.files['file']
# if user does not select file, browser also
# submit an empty part without filename
if file.filename == '':
return redirect(request.url)
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
return 'file uploaded successfully'
else:
return 'invalid file type'
@app.route('/download/<filename>', methods=['GET'])
def download_file(filename):
try:
return send_from_directory(app.config['UPLOAD_FOLDER'], filename, as_attachment=True)
except FileNotFoundError:
abort(404)
@app.route('/metrics', methods=['GET'])
def get_metrics():
file_list = os.listdir(app.config['UPLOAD_FOLDER'])
file_count = len(file_list)
total_size = 0
for filename in file_list:
total_size += os.path.getsize(os.path.join(app.config['UPLOAD_FOLDER'], filename))
return {
'file_count': file_count,
'total_size': total_size,
'files': [{
'name': filename,
'size': os.path.getsize(os.path.join(app.config['UPLOAD_FOLDER'], filename))
} for filename in file_list]
}
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5040, debug=True)
# Upload
# curl -X POST -H "Authorization: Bearer myuploadtoken" -F "file=@/path/to/file" http://docker10.grote.lan:5040/upload
# Download
# curl -X GET http://docker10.grote.lan:5040/download/filename.ext > filename.ext
# List
# curl -X GET http://docker10.grote.lan:5040/files
# Metriken
# curl -X GET http://docker10.grote.lan:5040/metrics
# upload check
# download
# farben im putput weg
# wsgi server