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

75 lines
2.3 KiB
Python
Raw Normal View History

2023-04-12 16:08:55 +02:00
import os
2023-04-13 11:03:56 +02:00
from flask import Flask, request, jsonify, send_file, render_template
2023-04-12 16:08:55 +02:00
app = Flask(__name__)
2023-04-13 11:03:56 +02:00
UPLOAD_DIRECTORY = os.environ.get("UPLOAD_DIRECTORY", "./uploads")
UPLOAD_TOKEN = os.environ.get("UPLOAD_TOKEN")
@app.route("/upload", methods=["POST"])
def upload():
if UPLOAD_TOKEN and "Token" not in request.headers:
return jsonify({"message": "No upload token provided"}), 401
token = request.headers.get("Token")
if UPLOAD_TOKEN and token != UPLOAD_TOKEN:
return jsonify({"message": "Invalid upload token"}), 401
if "file" not in request.files:
return jsonify({"message": "No file found"}), 400
file = request.files["file"]
if file.filename == "":
return jsonify({"message": "No file found"}), 400
if not os.path.exists(UPLOAD_DIRECTORY):
os.makedirs(UPLOAD_DIRECTORY)
file.save(os.path.join(UPLOAD_DIRECTORY, file.filename))
return jsonify({"message": "File saved successfully"}), 200
@app.route("/download/<filename>", methods=["GET"])
def download(filename):
file_path = os.path.join(UPLOAD_DIRECTORY, filename)
if not os.path.exists(file_path):
return jsonify({"message": "File not found"}), 404
return send_file(file_path, as_attachment=True)
@app.route("/", methods=["GET"])
def index():
2023-04-12 16:08:55 +02:00
files = []
2023-04-13 11:03:56 +02:00
for filename in os.listdir(UPLOAD_DIRECTORY):
filepath = os.path.join(UPLOAD_DIRECTORY, filename)
if os.path.isfile(filepath):
files.append({"name": filename, "size": os.path.getsize(filepath)})
return render_template("index.html", files=files)
@app.route("/metrics", methods=["GET"])
def metrics():
files = os.listdir(UPLOAD_DIRECTORY)
file_count = len(files)
total_size = sum(os.path.getsize(os.path.join(UPLOAD_DIRECTORY, f)) for f in files)
file_list = [{"name": f, "size": os.path.getsize(os.path.join(UPLOAD_DIRECTORY, f))} for f in files]
return jsonify({"count": file_count, "total_size": total_size, "files": file_list}), 200
# 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
2023-04-12 16:08:55 +02:00
2023-04-12 16:28:16 +02:00
# farben im putput weg
# wsgi server