__init__.py 1.5 KB

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