upload_to_oss.py 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. # -*- coding: utf-8 -*-
  2. import os
  3. import oss2
  4. import requests
  5. import uuid
  6. import time
  7. from config import *
  8. class TedOSS:
  9. def __init__(self):
  10. """
  11. """
  12. self.AccessKeyID = 'LTAIbkpKrzQViemJ'
  13. self.AccessKeySecret = '9y9mqNFMMDfUEBGvWqHt3wGas2W5ML'
  14. self.bucket_name = 'scxjcclub'
  15. self.root_name = 'say365'
  16. self.auth = oss2.Auth(self.AccessKeyID, self.AccessKeySecret)
  17. self.endpoint = 'http://oss-cn-beijing.aliyuncs.com'
  18. self.bucket = oss2.Bucket(self.auth, self.endpoint, self.bucket_name)
  19. self.domain = 'http://scxjcclub.oss-cn-beijing.aliyuncs.com'
  20. def upload_from_str(self,content_str=None,filename=None):
  21. '''
  22. 通过字符串上传
  23. byte,unicode,str
  24. '''
  25. filename = os.path.join(self.root_name,filename)
  26. result = self.bucket.put_object(filename,content_str)
  27. if result.status == 200:
  28. url = os.path.join(self.domain,filename)
  29. else:
  30. url = ''
  31. return url
  32. def upload_from_local(self, localfile=None, ossfile=None):
  33. '''
  34. 上传本地文件到oss
  35. '''
  36. ossfile = os.path.join(self.root_name, ossfile).replace("\\","/")
  37. with open(localfile, 'rb') as fileobj:
  38. result = self.bucket.put_object(ossfile, fileobj)
  39. if result.status == 200:
  40. url = os.path.join(self.domain, ossfile).replace("\\","/")
  41. else:
  42. url = ''
  43. xlog.info(url)
  44. return url
  45. def resumable_upload_from_local(self, localfile=None, ossfile=None):
  46. ossfile = os.path.join(self.root_name, ossfile)
  47. result = oss2.resumable_upload(self.bucket,ossfile,localfile,
  48. store=oss2.ResumableStore(root='/tmp'),
  49. multipart_threshold=100*1024,
  50. part_size=100*1024,
  51. num_threads=4,
  52. )
  53. print result.status
  54. if result.status == 200:
  55. url = os.path.join(self.domain,ossfile)
  56. else:
  57. url = ''
  58. return url
  59. def upload_from_url(self, url=None, ossfile=None):
  60. '''
  61. '''
  62. ossfile = os.path.join(self.root_name,ossfile)
  63. resp = requests.get(url)
  64. result = self.bucket.put_object(ossfile,resp)
  65. if result.status == 200:
  66. url = os.path.join(self.domain,ossfile)
  67. else:
  68. url = ''
  69. return url
  70. if __name__ == '__main__':
  71. myoss = TedOSS()
  72. localfile = 'D:\\docxdemo\\test.docx'
  73. ossfile = 'test.docx'
  74. url = myoss.upload_from_local(localfile,ossfile)
  75. print url