__init__.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. from configure import conf
  2. import oss2
  3. import logging.handlers
  4. import logging
  5. import os
  6. from urllib.parse import urljoin
  7. class Aliyun:
  8. def __init__(self, key, secret, endpoint, name, is_cname):
  9. self.key = key
  10. self.secret = secret
  11. self.auth = oss2.Auth(key, secret)
  12. self.bucket = oss2.Bucket(self.auth, endpoint, name, is_cname=is_cname)
  13. self.logger = logging.getLogger("main.aliyun")
  14. self.logger.setLevel(conf["LOG_LEVEL"])
  15. if len(conf["LOG_HOME"]) > 0:
  16. handle = logging.handlers.TimedRotatingFileHandler(
  17. os.path.join(conf["LOG_HOME"], f"aliyun.log"), backupCount=10)
  18. handle.setFormatter(logging.Formatter(conf["LOG_FORMAT"]))
  19. self.logger.addHandler(handle)
  20. def upload_file(self, name, f):
  21. res = self.bucket.put_object(name, f)
  22. self.logger.info(f"Upload {name} "
  23. f"id: {res.request_id} status: {res.status} "
  24. f"etag: {res.etag} resp: {res.resp} "
  25. f"version id: {res.versionid} key: {self.key}")
  26. def shared_obj(self, name, time=15):
  27. if not self.bucket.object_exists(name):
  28. return None
  29. if conf["ALIYUN_BUCKET_USE_SIGN_URL"]:
  30. url = self.bucket.sign_url('GET', name, time, slash_safe=True)
  31. else:
  32. url = urljoin(conf["ALIYUN_BUCKET_ENDPOINT"], name)
  33. self.logger.debug(f"Get url {url} name: {name} time: {time}s key: {self.key}")
  34. return url
  35. if conf["USE_ALIYUN"]:
  36. aliyun = Aliyun(conf["ALIYUN_KEY"],
  37. conf["ALIYUN_SECRET"],
  38. conf["ALIYUN_BUCKET_ENDPOINT"],
  39. conf["ALIYUN_BUCKET_NAME"],
  40. conf["ALIYUN_BUCKET_IS_CNAME"])
  41. else:
  42. aliyun = None