阿里云 oss python3 样例

阿里云的oss SDK又是不支持python3,头疼头疼。

本想改一改它的SDK,让它支持python2+python3,无奈里面大量的代码使用不带括号的print。工作量恐怖。

幸好oss的使用很easy。我翻了翻相关文档。弄了个简单可执行的样例(python2, python3都支持),基本的代码例如以下:aliyun-oss-python3

请注意,须要填写自己的accessKeyId等相关信息

import base64
import hmac
from hashlib import sha1
import time
try:
    import urllib.request as urllib
except ImportError:
    import urllib2 as urllib


accessKeyId = 'ic20Gwxms6ynLlkx'
accessKeySecret = 'lhTBND3SHvSawihEcIL6LFz597xtMj'
bucket = 'fast-loan'
region_host =  'oss-cn-hangzhou.aliyuncs.com'


# use signature in url
def _oss_file_url(method, bucket, filename, content_type):
    now = int(time.time())
    expire = now - (now % 1800) + 3600 # expire will not different every second
    tosign = "%s %d /%s/%s" % (method, expire, bucket, filename)
    if method == 'PUT' or method == 'POST':
        tosign = "%s %s %d /%s/%s" % (method, content_type, expire, bucket, filename)
    h = hmac.new(accessKeySecret.encode(), tosign.encode(), sha1)
    sign = urllib.quote(base64.encodestring(h.digest()).strip())
    return 'http://%s.%s/%s?OSSAccessKeyId=%s&Expires=%d&Signature=%s' % (
        bucket, region_host, filename, accessKeyId, expire, sign
    )


def get_file_url(bucket, filename):
    return _oss_file_url('GET', bucket, filename, None)


def http_put(bucket, filename, cont, content_type):
    url = _oss_file_url('PUT', bucket, filename, content_type)
    req = urllib.Request(url, cont)
    req.get_method = lambda: 'PUT'
    req.add_header('content-type', content_type)
    try:
        return urllib.urlopen(req)
    except urllib.HTTPError as e:
        print(e)


http_put(bucket, 'mytestkey', b'sample value', 'text/plain')
url = get_file_url(bucket, 'mytestkey')
print(urllib.urlopen(url).read())

原文地址:https://www.cnblogs.com/gcczhongduan/p/5336738.html