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:34:16 +02:00

75 lines
2.3 KiB
Python

import os
import uuid
from flask import Flask, request, jsonify, send_from_directory, render_template
app = Flask(__name__)
UPLOAD_DIRECTORY = os.environ.get("UPLOAD_DIRECTORY", "/uploads")
if not os.path.exists(UPLOAD_DIRECTORY):
os.makedirs(UPLOAD_DIRECTORY)
UPLOAD_TOKEN = os.environ.get("UPLOAD_TOKEN")
def allowed_file(filename):
return True
@app.route("/")
def index():
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 render_template("index.html", files=files, total_size=total_size, count=len(files))
@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})
@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)
# 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