routes.py 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. from flask import request, Blueprint
  2. from flask_restful import Resource, Api
  3. from os import path, remove, listdir
  4. import logging
  5. from models.config import STATIC_DIR
  6. statics_app = Blueprint('statics', __name__)
  7. api = Api(statics_app)
  8. logger = logging.getLogger(__name__)
  9. class StaticImg(Resource):
  10. IMG_DIR = path.join(STATIC_DIR, 'img')
  11. def post(self):
  12. img_data = request.files['image']
  13. img_dir = path.join(self.IMG_DIR,
  14. request.args.get('type', type=str),
  15. request.args.get('filename', type=str))
  16. img_data.save(img_dir)
  17. return {'filename': request.args.get('filename', type=str)}
  18. def delete(self):
  19. img_dir = path.join(self.IMG_DIR,
  20. request.args.get('type', type=str),
  21. request.args.get('filename', type=str))
  22. remove(img_dir)
  23. return {'filename': request.args.get('filename', type=str)}
  24. def get_static_imgs_src(type_):
  25. def allow_ext(filename):
  26. return '.' in filename and \
  27. filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
  28. result = []
  29. ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif', 'webp'}
  30. TYPE_IMG_DIR = path.join(STATIC_DIR, 'img', type_)
  31. base_src = path.join('/img', type_)
  32. for f in listdir(TYPE_IMG_DIR):
  33. if not allow_ext(f):
  34. continue
  35. result.append(path.join(base_src, f))
  36. return result
  37. api.add_resource(StaticImg, '/api/statics/img')