├── README.md └── oss_sample.py /README.md: -------------------------------------------------------------------------------- 1 | #oss使用例子 2 | 3 | 请填写阿里云里面的相关信息: 4 | 5 | * accessKeyId 6 | * accessKeySecret 7 | * bucket 8 | * region_host 9 | 10 | python oss_sample.py 11 | -------------------------------------------------------------------------------- /oss_sample.py: -------------------------------------------------------------------------------- 1 | import base64 2 | import hmac 3 | from hashlib import sha1 4 | import time 5 | try: 6 | import urllib.request as urllib 7 | except ImportError: 8 | import urllib2 as urllib 9 | 10 | accessKeyId = 'ic20Gwxms6ynLlkx' 11 | accessKeySecret = 'lhTBND3SHvSawihEcIL6LFz597xtMj' 12 | bucket = 'fast-loan' 13 | region_host = 'oss-cn-hangzhou.aliyuncs.com' 14 | 15 | # use signature in url 16 | def _oss_file_url(method, bucket, filename, content_type): 17 | now = int(time.time()) 18 | expire = now - (now % 1800) + 3600 # expire will not different every second 19 | tosign = "%s\n\n\n%d\n/%s/%s" % (method, expire, bucket, filename) 20 | if method == 'PUT' or method == 'POST': 21 | tosign = "%s\n\n%s\n%d\n/%s/%s" % (method, content_type, expire, bucket, filename) 22 | h = hmac.new(accessKeySecret.encode(), tosign.encode(), sha1) 23 | sign = urllib.quote(base64.encodestring(h.digest()).strip()) 24 | return 'http://%s.%s/%s?OSSAccessKeyId=%s&Expires=%d&Signature=%s' % ( 25 | bucket, region_host, filename, accessKeyId, expire, sign 26 | ) 27 | 28 | def get_file_url(bucket, filename): 29 | return _oss_file_url('GET', bucket, filename, None) 30 | 31 | 32 | def http_put(bucket, filename, cont, content_type): 33 | url = _oss_file_url('PUT', bucket, filename, content_type) 34 | req = urllib.Request(url, cont) 35 | req.get_method = lambda: 'PUT' 36 | req.add_header('content-type', content_type) 37 | try: 38 | return urllib.urlopen(req) 39 | except urllib.HTTPError as e: 40 | print(e) 41 | 42 | http_put(bucket, 'mytestkey', b'sample value', 'text/plain') 43 | url = get_file_url(bucket, 'mytestkey') 44 | print(urllib.urlopen(url).read()) --------------------------------------------------------------------------------