python-api-server/app.py

76 lines
2.3 KiB
Python
Raw Normal View History

2023-04-12 16:08:55 +02:00
import os
2023-04-13 11:34:16 +02:00
import uuid
from flask import Flask, request, jsonify, send_from_directory, render_template
2023-04-13 11:03:56 +02:00
2023-04-13 11:29:47 +02:00
app = Flask(__name__)
2023-04-13 11:34:16 +02:00
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")
2023-04-13 11:03:56 +02:00
2023-04-13 11:29:47 +02:00
def allowed_file(filename):
2023-04-13 11:34:16 +02:00
return True
2023-04-13 11:03:56 +02:00
2023-04-13 11:34:16 +02:00
@app.route("/")
2023-04-13 11:03:56 +02:00
def index():
2023-04-13 11:34:16 +02:00
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)
2023-04-13 11:03:56 +02:00
# 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
2023-04-13 11:29:47 +02:00
# curl -X GET http://docker10.grote.lan:5040/files
2023-04-13 11:03:56 +02:00
# Metriken
# curl -X GET http://docker10.grote.lan:5040/metrics
2023-04-12 16:08:55 +02:00
2023-04-12 16:28:16 +02:00
2023-04-13 11:29:47 +02:00
# upload check
# download
2023-04-12 16:28:16 +02:00
# farben im putput weg
# wsgi server