minio_handler.py 3.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. import base64
  2. import io
  3. from minio import Minio
  4. from minio.error import (ResponseError, BucketAlreadyOwnedByYou,
  5. BucketAlreadyExists, NoSuchKey)
  6. from PIL import Image
  7. from io import BytesIO
  8. URL = 'minio-api.sxkj.com'
  9. ACCESS_KEY = 'admin'
  10. SECRET_KEY = 'sxkjadmin'
  11. class FileHandler(object):
  12. def __init__(self, bucket_name):
  13. self.bucket_name = bucket_name
  14. self.minio_client = Minio(URL,
  15. access_key=ACCESS_KEY,
  16. secret_key=SECRET_KEY,
  17. secure=False)
  18. # 无脑创桶
  19. try:
  20. self.minio_client.make_bucket(self.bucket_name)
  21. except BucketAlreadyExists:
  22. pass
  23. except BucketAlreadyOwnedByYou:
  24. pass
  25. except ResponseError:
  26. raise Exception("minio连接失败")
  27. # 上传图片
  28. def put_image(self, img_name, image):
  29. file_name = img_name
  30. file_byte = base64.b64decode(image)
  31. f = io.BytesIO(file_byte)
  32. try:
  33. self.minio_client.put_object(self.bucket_name, file_name, f, len(file_byte))
  34. return file_name
  35. except ResponseError:
  36. raise Exception("minio创建图片失败 文件名:%s" % file_name)
  37. def put_byte_file(self, file_name, file_content):
  38. f = io.BytesIO(file_content)
  39. try:
  40. self.minio_client.put_object(self.bucket_name, file_name, f, len(file_content))
  41. return file_name
  42. except ResponseError:
  43. raise Exception("minio创建文件失败 文件名:%s" % file_name)
  44. def put_np_image(self, img_name, np_image):
  45. file_name = img_name
  46. img_crop_pil = Image.fromarray(np_image)
  47. byte_io = BytesIO()
  48. img_crop_pil.save(byte_io, format="jpeg")
  49. jpg_buffer = byte_io.getvalue()
  50. byte_io = BytesIO(jpg_buffer)
  51. try:
  52. self.minio_client.put_object(self.bucket_name, img_name, byte_io, len(jpg_buffer))
  53. return file_name
  54. except ResponseError:
  55. raise Exception("minio创建图片失败 文件名:%s" % file_name)
  56. # 获取照片
  57. def get_file(self, img_name):
  58. file_name = img_name
  59. try:
  60. d = self.minio_client.get_object(self.bucket_name, file_name)
  61. return d.data
  62. except NoSuchKey:
  63. pass
  64. except Exception as e:
  65. print("Get minio pic failed:{}".format(e))
  66. return bytes()
  67. def del_image(self, img_name):
  68. file_name = img_name
  69. try:
  70. self.minio_client.remove_object(self.bucket_name, file_name)
  71. except ResponseError:
  72. raise Exception("删除minio图片失败 文件名:%s" % file_name)
  73. def ls_file(self, filename):
  74. objects = []
  75. try:
  76. objects = self.minio_client.list_objects(self.bucket_name, prefix=filename,
  77. recursive=True)
  78. except ResponseError:
  79. raise Exception("列出文件失败")
  80. finally:
  81. return objects