码迷,mamicode.com
首页 > 编程语言 > 详细

阿里云 oss python3 例子

时间:2015-07-22 19:03:01      阅读:220      评论:0      收藏:0      [点我收藏+]

标签:阿里云   python   sdk   

阿里云的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())

版权声明:本文为博主原创文章,未经博主允许不得转载。

阿里云 oss python3 例子

标签:阿里云   python   sdk   

原文地址:http://blog.csdn.net/dongfuye/article/details/47004849

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!