Guest User

Untitled

a guest
Oct 8th, 2018
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 6.63 KB | None | 0 0
  1. # -*- coding: utf-8 -*-
  2.  
  3. import md5 as mmd5
  4.  
  5.  
  6. DEBUG = False
  7.  
  8. api_upyun = 'api.upyun.com'
  9. ENDPOINT_V0 = 'v0.' + api_upyun
  10. ENDPOINT_V1 = 'v1.' + api_upyun
  11. ENDPOINT_V2 = 'v2.' + api_upyun
  12. ENDPOINT_V3 = 'v3.' + api_upyun
  13. default_endpoint = ENDPOINT_V0
  14.  
  15.  
  16. def md5(e):
  17. m = mmd5.new()
  18. m.update(e)
  19. return m.hexdigest()
  20.  
  21.  
  22. def md5_fd(fobj):
  23. m = mmd5.new()
  24. while True:
  25. data = fobj.read(8096)
  26. if not data:
  27. break
  28. m.update(data)
  29. fobj.seek(0)
  30. return m.hexdigest()
  31.  
  32.  
  33. def set_endpoint(e):
  34. global default_endpoint
  35. default_endpoint = e
  36.  
  37.  
  38. def get_endpoint():
  39. return default_endpoint
  40.  
  41.  
  42. class UpyunCore(object):
  43. def __init__(self, auth_type='upyun'):
  44. self._auth_type = auth_type
  45.  
  46. def _basic_auth(self, headers, username, password):
  47. import base64
  48. data = base64.encodestring(username + ':' + password).strip()
  49. headers['Authorization'] = 'Basic ' + data
  50.  
  51. def _upyun_auth(self, headers, method, path, username, password):
  52. import time
  53. headers['Date'] = time.strftime('%a, %d %b %Y %X GMT', time.gmtime())
  54. content_length = headers.get('Content-Length') or 0
  55. signature = '&'.join([method, path, headers['Date'], str(content_length),
  56. md5(password)])
  57. headers['Authorization'] = 'UpYun %s:%s' % (username, md5(signature))
  58.  
  59. def request(self, host, method, path, data, username, password, options):
  60. import httplib
  61. headers = options.copy()
  62. if self._auth_type == 'basic':
  63. self._basic_auth(headers, username, password)
  64. else:
  65. self._upyun_auth(headers, method, path, username, password)
  66. conn = httplib.HTTPConnection(host)
  67. conn.request(method, path, data, headers)
  68. res = conn.getresponse()
  69. if DEBUG:
  70. print '%s %s => %s %s' % (method, host + path, res.status, res.reason)
  71. return res
  72.  
  73.  
  74. class UpyunEntry(object):
  75. def __init__(self, name, type, size, date):
  76. self.name = name
  77. self.type = 'folder' if type == 'F' else 'file'
  78. self.size = size
  79. self.date = date
  80.  
  81. def __str__(self):
  82. return '<%s: %s>' % (self.type, self.name)
  83.  
  84.  
  85. class Upyun(object):
  86. def __init__(self, bucket, username, password, transport=UpyunCore()):
  87. self._bucket = bucket
  88. self._username = username
  89. self._password = password
  90. self._core = transport
  91.  
  92. def __str__(self):
  93. return '<bucket: %s, username: %s>' % (self._bucket, self._username)
  94.  
  95. def touch(self, path, data, md5_checksum=None, auto_mkdir=False):
  96. options = {}
  97. if md5_checksum:
  98. headers['Content-MD5'] = md5_checksum
  99. if auto_mkdir:
  100. options['mkdir'] = 'true'
  101. if type(data) != file:
  102. options['Content-Length'] = len(data)
  103. res = self._request('PUT', self._generate_path(path), data, options)
  104. return self._is_res_ok(res)
  105.  
  106. def touch_image(self, path, data, secret_code=None,
  107. md5_checksum=None, auto_mkdir=False):
  108. options = {}
  109. if secret_code:
  110. headers['Content-Secret'] = secret_code
  111. if md5_checksum:
  112. headers['Content-MD5'] = md5_checksum
  113. if auto_mkdir:
  114. options['mkdir'] = 'true'
  115. if type(data) != file:
  116. options['Content-Length'] = len(data)
  117. res = self._request('PUT', self._generate_path(path), data, options)
  118. if self._is_res_ok(res):
  119. info = {}
  120. info['x-upyun-width'] = res.getheader('x-upyun-width')
  121. info['x-upyun-height'] = res.getheader('x-upyun-height')
  122. info['x-upyun-frames'] = res.getheader('x-upyun-frames')
  123. info['x-upyun-file-type'] = res.getheader('x-upyun-file-type')
  124. return True, info
  125. return False, self._get_res_errmsg(res)
  126.  
  127. def cat(self, path):
  128. res = self._request('GET', self._generate_path(path))
  129. if self._is_res_ok(res):
  130. return True, res.read()
  131. return False, self._get_res_errmsg(res)
  132.  
  133. def stat(self, path):
  134. res = self._request('HEAD', self._generate_path(path))
  135. if self._is_res_ok(res):
  136. info = {}
  137. info['type'] = res.getheader('x-upyun-file-type')
  138. info['size'] = res.getheader('x-upyun-file-size')
  139. info['date'] = res.getheader('x-upyun-file-date')
  140. return True, info
  141. return False, self._get_res_errmsg(res)
  142.  
  143. def usage(self, path='/'):
  144. res = self._request('GET', self._generate_path(path) + '?usage')
  145. if self._is_res_ok(res):
  146. return True, int(res.read())
  147. return False, self._get_res_errmsg(res)
  148.  
  149. def ls(self, path='/'):
  150. res = self._request('GET', self._generate_path(path))
  151. if self._is_res_ok(res):
  152. data = res.read()
  153. for e in data.split('\n'):
  154. info_lst = e.split('\t')
  155. if len(info_lst) >= 4:
  156. yield UpyunEntry(*info_lst)
  157.  
  158. def mkdir(self, path, auto_mkdir=False):
  159. options = {}
  160. options['folder'] = 'create'
  161. if auto_mkdir:
  162. options['mkdir'] = 'true'
  163. res = self._request('POST', self._generate_path(path), None, options)
  164. return self._is_res_ok(res)
  165.  
  166. def rmdir(self, path):
  167. return self.rm(path)
  168.  
  169. def rm(self, path):
  170. res = self._request('DELETE', self._generate_path(path))
  171. return self._is_res_ok(res)
  172.  
  173. def _is_res_ok(self, res):
  174. return res.status == 200
  175.  
  176. def _get_res_errmsg(self, res):
  177. return '%s %s: %s' % (res.status, res.reason, res.read())
  178.  
  179. def _request(self, method, path, data=None, options={}):
  180. return self._core.request(get_endpoint(), method, path, data,
  181. self._username, self._password,
  182. options)
  183.  
  184. def _generate_path(self, filename=None):
  185. path = '/' + self._bucket
  186. return path + filename if filename else path
  187.  
  188.  
  189. if __name__ == '__main__':
  190. s = Upyun('<bucket-name>', '<operator-name>', '<operator-pwd>')
  191. # endpoint
  192. print 'endpoint: %s' % get_endpoint()
  193. set_endpoint(ENDPOINT_V1)
  194. print 'endpoint: %s' % get_endpoint()
  195. # usage
  196. rc, usage = s.usage()
  197. if rc:
  198. print 'usage: %d' % usage
  199. # mkdir
  200. s.mkdir('/tmp')
  201. s.mkdir('/tmp/1/2', True)
  202. # rmdir
  203. s.rmdir('/tmp/1/2')
  204. s.rmdir('/tmp/1')
  205. s.rmdir('/tmp')
  206. # touch
  207. s.touch('/a.txt', 'hijcak')
  208. # cat
  209. rc, data = s.cat('/a.txt')
  210. if rc:
  211. print 'data of a.txt is: ' + data
  212. # stat
  213. rc, info = s.stat('/a.txt')
  214. if rc:
  215. print info
  216. # rm
  217. s.rm('/a.txt')
  218. # ls
  219. for e in s.ls():
  220. print e
Add Comment
Please, Sign In to add comment