您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

azure_sas_conn.py 2.5KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. import os
  2. import time
  3. from io import BytesIO
  4. from rag import settings
  5. from rag.settings import azure_logger
  6. from rag.utils import singleton
  7. from azure.storage.blob import ContainerClient
  8. @singleton
  9. class RAGFlowAzureSasBlob(object):
  10. def __init__(self):
  11. self.conn = None
  12. self.container_url = os.getenv('CONTAINER_URL', settings.AZURE["container_url"])
  13. self.sas_token = os.getenv('SAS_TOKEN', settings.AZURE["sas_token"])
  14. self.__open__()
  15. def __open__(self):
  16. try:
  17. if self.conn:
  18. self.__close__()
  19. except Exception as e:
  20. pass
  21. try:
  22. self.conn = ContainerClient.from_container_url(self.container_url + "?" + self.sas_token)
  23. except Exception as e:
  24. azure_logger.error(
  25. "Fail to connect %s " % self.container_url + str(e))
  26. def __close__(self):
  27. del self.conn
  28. self.conn = None
  29. def health(self):
  30. bucket, fnm, binary = "txtxtxtxt1", "txtxtxtxt1", b"_t@@@1"
  31. return self.conn.upload_blob(name=fnm, data=BytesIO(binary), length=len(binary))
  32. def put(self, bucket, fnm, binary):
  33. for _ in range(3):
  34. try:
  35. return self.conn.upload_blob(name=fnm, data=BytesIO(binary), length=len(binary))
  36. except Exception as e:
  37. azure_logger.error(f"Fail put {bucket}/{fnm}: " + str(e))
  38. self.__open__()
  39. time.sleep(1)
  40. def rm(self, bucket, fnm):
  41. try:
  42. self.conn.delete_blob(fnm)
  43. except Exception as e:
  44. azure_logger.error(f"Fail rm {bucket}/{fnm}: " + str(e))
  45. def get(self, bucket, fnm):
  46. for _ in range(1):
  47. try:
  48. r = self.conn.download_blob(fnm)
  49. return r.read()
  50. except Exception as e:
  51. azure_logger.error(f"fail get {bucket}/{fnm}: " + str(e))
  52. self.__open__()
  53. time.sleep(1)
  54. return
  55. def obj_exist(self, bucket, fnm):
  56. try:
  57. return self.conn.get_blob_client(fnm).exists()
  58. except Exception as e:
  59. azure_logger.error(f"Fail put {bucket}/{fnm}: " + str(e))
  60. return False
  61. def get_presigned_url(self, bucket, fnm, expires):
  62. for _ in range(10):
  63. try:
  64. return self.conn.get_presigned_url("GET", bucket, fnm, expires)
  65. except Exception as e:
  66. azure_logger.error(f"fail get {bucket}/{fnm}: " + str(e))
  67. self.__open__()
  68. time.sleep(1)
  69. return