-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
70 lines (53 loc) · 2.1 KB
/
server.py
File metadata and controls
70 lines (53 loc) · 2.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import os
import shutil
from flask import Flask, jsonify, redirect, request, send_from_directory, url_for
from werkzeug.utils import secure_filename
UPLOAD_FOLDER = os.path.join(os.getcwd(), "blob")
ALLOWED_EXTENSIONS = {"pdf", "png", "jpg", "jpeg"}
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
def mkdir(parent_dir: str, dir: str) -> None:
try:
path = os.path.join(parent_dir, dir)
os.mkdir(path)
except FileExistsError:
pass
@app.post("/upload/<uuid:event_uuid>")
def upload_file(event_uuid):
if "file" not in request.files:
return jsonify({"message": "No selected part"}), 400
file = request.files["file"]
if file.filename == "":
return jsonify({"message": "No selected file"}), 400
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
mkdir(app.config["UPLOAD_FOLDER"], str(event_uuid))
path = os.path.join(app.config["UPLOAD_FOLDER"], str(event_uuid), filename)
file.save(path)
return (
jsonify({"message": "File uploaded successfully", "filename": filename}),
200,
)
return (jsonify({"message": "Upload failed"}), 400)
@app.get("/images/<uuid:event_uuid>/<filename>")
def download_file(event_uuid, filename):
path = os.path.join(app.config["UPLOAD_FOLDER"], str(event_uuid))
return send_from_directory(path, filename)
@app.delete("/images/<uuid:event_uuid>/<filename>")
def delete_file(event_uuid, filename):
path = os.path.join(app.config["UPLOAD_FOLDER"], str(event_uuid), filename)
os.remove(path)
return (
jsonify({"message": "File deleted successfully", "filename": filename}),
200,
)
@app.delete("/images/<uuid:event_uuid>")
def delete_all_files(event_uuid):
path = os.path.join(app.config["UPLOAD_FOLDER"], str(event_uuid))
shutil.rmtree(path)
return (
jsonify({"message": "Event deleted successfully", "event_uuid": event_uuid}),
200,
)