Exemplo n.º 1
0
class OSSUploader(Uploader):

    def __init__(self):
        self.dirname = ''
        endpoint = current_app.config['OSS_ENDPOINT']
        key_id = current_app.config['KEY_ID']
        key_secret = current_app.config['KEY_SECRET']
        self.bucket_name = current_app.config['OSS_BUCKET_NAME']
        self.oss = OssAPI(endpoint, key_id, key_secret)
    
    def _store(self, fullname, data):
        self.oss.put_object_from_string(self.bucket_name, fullname, data)

    def remove(self, filename):
        fullname = os.path.join(self.dirname, filename)
        self.oss.delete_object(self.bucket_name, fullname)
Exemplo n.º 2
0
class OssFile(object):
    def __init__(self, conf):
        self.conf = conf
        self.oss = OssAPI(
            conf['host'],
            conf['access_id'],
            conf['secret_access_key'],
        )

    def get_link(self, path):
        return self.conf['link'] % path

    def get(self, name):
        res = self.oss.get_object(self.conf['bucket'], name)
        if (res.status / 100) == 2:
            return res.read()
        return ''

    def put(self, name, content, type=None):
        if type is not None:
            path = '%s.%s' % (name, type)
        else:
            path = name

        res = self.oss.put_object_from_string(self.conf['bucket'], path,
                                              content)
        if (res.status / 100) == 2:
            return path
        return ''

    def remove(self, name):
        res = self.oss.delete_object(self.conf['bucket'], name)
        if (res.status / 100) == 2:
            return True
        return False
Exemplo n.º 3
0
class OssFile(object):

	def __init__(self, conf):
		self.conf = conf
		self.oss = OssAPI(
			conf['host'],
			conf['access_id'],
			conf['secret_access_key'],
		)

	def get_link(self, path):
		return self.conf['link'] % path

	def get(self, name):
		res = self.oss.get_object(self.conf['bucket'], name)
		if (res.status / 100) == 2:
			return res.read()
		return ''

	def put(self, name, content, type=None):
		if type is not None:
			path = '%s.%s' % (name, type)
		else:
			path = name
			
		res = self.oss.put_object_from_string(self.conf['bucket'], path, content)
		if (res.status / 100) == 2:
			return path
		return ''

	def remove(self, name):
		res = self.oss.delete_object(self.conf['bucket'], name)
		if (res.status / 100) == 2:
			return True
		return False
Exemplo n.º 4
0
class OSSFile(BaseFile):
    def __init__(self, conf):
        super(OSSFile, self).__init__(conf)
        from oss.oss_api import OssAPI
        self.oss = OssAPI(
            conf['host'],
            conf['access_id'],
            conf['secret_access_key'],
        )

    def get_link(self,
                 name,
                 width=0,
                 height=0,
                 ystart=0,
                 yend=0,
                 source=False):
        link = self.conf['link'] % name
        if source:
            return link

        format = name.split('.')[-1]
        if format not in ['jpg', 'jpeg', 'png', 'gif', 'bmp']:
            format = 'jpg'

        attrs = []
        if width != 0:
            attrs.append('w_%d' % width)
        if height != 0:
            attrs.append('h_%d' % height)
        if attrs:
            if width and height:
                attrs.append('m_fill')
            attrs.append('limit_0')
        if attrs:
            return link + '?x-oss-process=image/resize,' + \
                ','.join(attrs) + '/format,' + format
        return link

    def get(self, name):
        res = self.oss.get_object(self.conf['bucket'], name)
        if (res.status / 100) == 2:
            return res.read()
        return ''

    def put(self, name, content, type=None):
        name = '%s.%s' % (name, type) if type is not None else name
        if not name.startswith(self.conf.get('prefix')):
            name = self.conf.get('prefix', '') + name
        res = self.oss.put_object_from_string(self.conf['bucket'], name,
                                              content)
        if (res.status / 100) == 2:
            return name
        current_app.logger.error('oss error: \n' + res.read())
        return ''

    def remove(self, name):
        res = self.oss.delete_object(self.conf['bucket'], name)
        return (res.status / 100) == 2
Exemplo n.º 5
0
class OSSFile(BaseFile):
    def __init__(self, conf):
        super(OSSFile, self).__init__(conf)
        from oss.oss_api import OssAPI
        self.oss = OssAPI(
            conf['host'],
            conf['access_id'],
            conf['secret_access_key'],
        )

    def get_link(self,
                 name,
                 width=0,
                 height=0,
                 ystart=0,
                 yend=0,
                 source=False):
        link = self.conf['link'] % name
        if source:
            return link

        format = name.split('.')[-1]
        if format not in ['jpg', 'jpeg', 'png', 'gif', 'bmp']:
            format = 'jpg'

        attrs = []
        if ystart != 0 and yend != 0:
            attrs.append('@0-%d-0-%da' % (ystart, yend))
        if width != 0: attrs.append('%dw' % width)
        if height != 0: attrs.append('%dh' % height)
        if attrs: attrs.append('1e_1c')
        if attrs or format != 'gif': attrs.append('95Q')
        if attrs:
            if format == 'gif': format = 'jpg'
            return link + '@' + '_'.join(attrs) + '.' + format
        return link

    def get(self, name):
        res = self.oss.get_object(self.conf['bucket'], name)
        if (res.status / 100) == 2:
            return res.read()
        return ''

    def put(self, name, content, type=None):
        name = '%s.%s' % (name, type) if type is not None else name
        if not name.startswith(self.conf.get('prefix')):
            name = self.conf.get('prefix', '') + name
        res = self.oss.put_object_from_string(self.conf['bucket'], name,
                                              content)
        if (res.status / 100) == 2:
            return name
        current_app.logger.error('oss error: \n' + res.read())
        return ''

    def remove(self, name):
        res = self.oss.delete_object(self.conf['bucket'], name)
        return (res.status / 100) == 2
Exemplo n.º 6
0
def alioss_file_util(optype, fpath, content = ""):
    from oss.oss_api import OssAPI
    bucketname = settings["oss_bucket_name"]
    endpoint = settings["oss_endpoint"]
    accessKeyId, accessKeySecret = settings['oss_accessKeyId'], settings['oss_accessKeySecret']
    oss = OssAPI(endpoint, accessKeyId, accessKeySecret)
    if optype == 'read':
        res = oss.get_object(bucketname, fpath)
        return res.read() or ""
    elif optype == 'write':
        res = oss.put_object_from_string(bucketname, fpath, content)
        return True
    return ''
Exemplo n.º 7
0
    def upload_file(self, file_data, file_path, content_type=None):
        """上传文件到oss服务器上

        :param file_data: 文件的数据
        :param file_path: 保存到OSS的路径
        :return:
        """
        oss = OssAPI(self.regional_node, self.id, self.key)
        expires = format_timestamp(datetime.datetime.today() + datetime.timedelta(days=+90))
        header = {'expires': expires,
                  'Cache-Control': 'max-age=%s' % (90*24*60*60)}
        if content_type:
            res = oss.put_object_from_string(self.bucket, file_path, file_data, headers=header, content_type=content_type)
        else:
            res = oss.put_object_from_string(self.bucket, file_path, file_data)
        if 200 == res.status:
            return True, file_path
        else:
            # log
            res_message = "OSS ERROR\n%s\n%s" % (res.status, res.read())
            logging.info(res_message)
            return False, u'上传文件出错!'
Exemplo n.º 8
0
class OSSFile(BaseFile):

    def __init__(self, conf):
        super(OSSFile, self).__init__(conf)
        from oss.oss_api import OssAPI
        self.oss = OssAPI(
            conf['host'],
            conf['access_id'],
            conf['secret_access_key'],
        )

    def get_link(self, name, width=0, height=0, ystart=0, yend=0, source=False):
        link = self.conf['link'] % name
        if source:
            return link

        format = name.split('.')[-1]
        if format not in ['jpg', 'jpeg', 'png', 'gif', 'bmp']:
            format = 'jpg'

        attrs = []
        if width != 0:
            attrs.append('w_%d' % width)
        if height != 0:
            attrs.append('h_%d' % height)
        if attrs:
            attrs.append('m_fill')
            attrs.append('limit_0')
        if attrs:
            return link + '?x-oss-process=image/resize,' + ','.join(attrs) + '/format,' + format
        return link

    def get(self, name):
        res = self.oss.get_object(self.conf['bucket'], name)
        if (res.status / 100) == 2:
            return res.read()
        return ''

    def put(self, name, content, type=None):
        name = '%s.%s' % (name, type) if type is not None else name
        if not name.startswith(self.conf.get('prefix')):
            name = self.conf.get('prefix', '') + name
        res = self.oss.put_object_from_string(self.conf['bucket'], name, content)
        if (res.status / 100) == 2:
            return name
        current_app.logger.error('oss error: \n' + res.read())
        return ''

    def remove(self, name):
        res = self.oss.delete_object(self.conf['bucket'], name)
        return (res.status / 100) == 2
Exemplo n.º 9
0
class OSSFile(BaseFile):
    
    def __init__(self, conf):
        super(OSSFile, self).__init__(conf)
        from oss.oss_api import OssAPI
        self.oss = OssAPI(
            conf['host'],
            conf['access_id'],
            conf['secret_access_key'],
        )

    def get_link(self, name, width=0, height=0, ystart=0, yend=0, source=False):
        link = self.conf['link'] % name
        if source:
            return link

        format = name.split('.')[-1]
        if format not in ['jpg', 'jpeg', 'png', 'gif', 'bmp']:
            format = 'jpg'

        attrs = []
        if ystart != 0 and yend != 0: attrs.append('@0-%d-0-%da' % (ystart, yend))
        if width != 0: attrs.append('%dw' % width)
        if height != 0: attrs.append('%dh' % height)
        if attrs: attrs.append('1e_1c')
        if attrs or format != 'gif': attrs.append('95Q')
        if attrs:
            if format == 'gif': format = 'jpg'
            return link + '@' + '_'.join(attrs) + '.' + format
        return link

    def get(self, name):
        res = self.oss.get_object(self.conf['bucket'], name)
        if (res.status / 100) == 2:
            return res.read()
        return ''

    def put(self, name, content, type=None):
        name = '%s.%s' % (name, type) if type is not None else name
        if not name.startswith(self.conf.get('prefix')):
            name = self.conf.get('prefix', '') + name
        res = self.oss.put_object_from_string(self.conf['bucket'], name, content)
        if (res.status / 100) == 2:
            return name
        return ''

    def remove(self, name):
        res = self.oss.delete_object(self.conf['bucket'], name)
        return (res.status / 100) == 2
Exemplo n.º 10
0
class AliOss(object):
    def __init__(self, access_key, access_key_secret, bucket, endpoint):
        self.access_key = access_key
        self.access_key_secret = access_key_secret
        self.bucket = bucket
        self.endpoint = endpoint
        self.oss = OssAPI(endpoint, access_key, access_key_secret)

    def put_user_avatar(self, user_id, avatar):
        content_type = avatar['content_type']
        file_format = avatar['filename'].split('.').pop().lower()
        file_name = '%s_%s' % (user_id, int(time.time()))
        file_dir = 'avatar/user/%s.%s' % (file_name, file_format)
        res = self.oss.put_object_from_string(self.bucket, file_dir,
                                              avatar['body'], content_type)
        if res.status == 200:
            return file_dir

    def put_room_avatar(self, user_id, avatar):
        content_type = avatar['content_type']
        file_format = avatar['filename'].split('.').pop().lower()
        file_name = '%s_%s' % (user_id, int(time.time()))
        file_dir = 'avatar/room/%s.%s' % (file_name, file_format)
        res = self.oss.put_object_from_string(self.bucket, file_dir,
                                              avatar['body'], content_type)
        if res.status == 200:
            return file_dir

    def put_validate(self, user_id, validate):
        content_type = validate['content_type']
        file_format = validate['filename'].split('.').pop().lower()
        file_name = '%s_%s%s' % (user_id, int(time.time()), createNoncestr())
        m = hashlib.md5()
        m.update(file_name)
        file_name = m.hexdigest()
        file_dir = 'validate/%s.%s' % (file_name, file_format)
        res = self.oss.put_object_from_string(self.bucket, file_dir,
                                              validate['body'], content_type)
        if res.status == 200:
            return file_dir

    def put_images(self, user_id, files):
        file_dirs = []
        now = datetime.now()
        date_str = now.strftime('%Y%m%d_%H')
        img_dir = 'images/%s/' % date_str
        for file in files:
            file_name = file['filename']
            content_type = file['content_type']
            file_format = file['filename'].split('.').pop().lower()
            hash_str = '%s%s%s' % (int(time.time()), user_id, file_name)
            m = hashlib.md5()
            m.update(hash_str)
            m_digest = m.hexdigest()
            md5_file_name = '%s.%s' % (m_digest, file_format)
            object_path = img_dir + md5_file_name
            res = self.oss.put_object_from_string(self.bucket, object_path,
                                                  file['body'], content_type)
            if res.status == 200:
                file_dirs.append(object_path)

        return file_dirs

    def put_video(self, user_id, video):
        content_type = video['content_type']
        file_format = video['filename'].split('.').pop().lower()
        file_name = '%s_%s' % (user_id, int(time.time()))
        file_dir = 'video/%s.%s' % (file_name, file_format)
        res = self.oss.put_object_from_string(self.bucket, file_name,
                                              video['body'], content_type)
        if res.status == 200:
            return file_dir