Browse Source

photos upload

lyc8503 4 years ago
parent
commit
0280cdd273

+ 3 - 0
.gitignore

@@ -30,3 +30,6 @@ pnpm-debug.log*
 /backend/capture_image/
 /backend/images/
 /backend/demo.mp4
+
+# 缓存文件
+/backend_refactor/upload

+ 34 - 0
backend_refactor/app.py

@@ -0,0 +1,34 @@
+import logging
+
+from flask import Flask
+
+import route.upload
+from config import VERSION_PREFIX, MAX_CONTENT_LENGTH
+from route.util import make_response
+
+app = Flask(__name__)
+app.config['MAX_CONTENT_LENGTH'] = MAX_CONTENT_LENGTH
+
+
+@app.route("/")
+def hello_world():
+    return "<p>Hello, World!</p>"
+
+
+app.register_blueprint(route.upload.bp, url_prefix=VERSION_PREFIX)
+
+
+@app.errorhandler(413)
+def error_handler(e):
+    logging.exception(e)
+    return make_response(413, "entity too large, max acceptable: " + str(MAX_CONTENT_LENGTH) + " bytes", {}, 413)
+
+
+@app.errorhandler(Exception)
+def error_handler(e):
+    logging.exception(e)
+    return make_response(500, "unknown internal server error.", {}, 500)
+
+
+if __name__ == '__main__':
+    app.run()

+ 3 - 0
backend_refactor/config/__init__.py

@@ -0,0 +1,3 @@
+VERSION_PREFIX = "/v1/"
+UPLOAD_DIR = "./upload/"
+MAX_CONTENT_LENGTH = 100 * 1024 * 1024

+ 0 - 0
backend_refactor/route/__init__.py


+ 52 - 0
backend_refactor/route/upload.py

@@ -0,0 +1,52 @@
+import logging
+import uuid
+
+from flask import request, Blueprint
+
+from config import UPLOAD_DIR
+from route.util import make_response
+
+from PIL import Image
+
+bp = Blueprint("upload", __name__, url_prefix='/')
+
+
+def upload(type):
+    # 检查是否正确上传了文件
+    if 'file' not in request.files:
+        return make_response(400, "no file part.", {}, 400)
+
+    file = request.files['file']
+    if file.filename == '':
+        return make_response(400, "no selected file.", {}, 400)
+
+    # 随机 uuid 名称
+    random_name = str(uuid.uuid4())
+
+    # 图片格式检查 & 转换
+    if type == "photo":
+        try:
+            img = Image.open(file.stream)
+            img.verify()
+            img = Image.open(file.stream)
+            img = img.convert("RGB")
+            img.save(open(UPLOAD_DIR + random_name + ".jpg", "wb"))
+        except Exception as e:
+            logging.exception(e)
+            return make_response(-1, "cannot identify image file.", {})
+    elif type == "video":
+        pass
+    else:
+        assert False, "未知上传格式"
+
+    return make_response(0, "success", {"uuid": random_name})
+
+
+@bp.route("/photos", methods=["POST"])
+def upload_photo():
+    return upload("photo")
+
+
+@bp.route("/videos", methods=["POST"])
+def upload_video():
+    return upload("video")

+ 11 - 0
backend_refactor/route/util.py

@@ -0,0 +1,11 @@
+from flask import Response, jsonify
+
+
+def make_response(status: int, msg: str, return_data: dict, http_status_code=200) -> Response:
+    """
+    标准请求返回
+    :return: Response
+    """
+    ret = jsonify({"code": status, "msg": msg, "data": return_data})
+    ret.status_code = http_status_code
+    return ret