阿里云 oss python3 例子

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

幸好oss的使用非常简单,我翻了翻相关文档,弄了个简单可运行的例子(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\n\n\n%d\n/%s/%s" % (method, expire, bucket, filename)
    if method == 'PUT' or method == 'POST':
        tosign = "%s\n\n%s\n%d\n/%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())

©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页