当前位置: 首页>>代码示例>>Python>>正文


Python Bucket.generate_url方法代码示例

本文整理汇总了Python中sae.storage.Bucket.generate_url方法的典型用法代码示例。如果您正苦于以下问题:Python Bucket.generate_url方法的具体用法?Python Bucket.generate_url怎么用?Python Bucket.generate_url使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在sae.storage.Bucket的用法示例。


在下文中一共展示了Bucket.generate_url方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: put_obj2storage

# 需要导入模块: from sae.storage import Bucket [as 别名]
# 或者: from sae.storage.Bucket import generate_url [as 别名]
def put_obj2storage(file_name = '', data = '', expires='365', type=None, encoding= None, domain_name = setting.STORAGE_DOMAIN_NAME):
    import sae.const  
    access_key = sae.const.ACCESS_KEY  
    secret_key = sae.const.SECRET_KEY  
    appname = sae.const.APP_NAME  
    domain_name = "attachment" 
    bucket = Bucket(domain_name)
    bucket.put()
    bucket.post(metadata={'expires': '2d'})
    attrs = bucket.stat()
    bucket.put_object(file_name, data)
    file_url = bucket.generate_url(file_name)
    #begin to created
    im = Image.open("/s/attachment/" + file_name)
    #im = Image.open(bucket.get_object_contents(file_name))
    im.thumbnail((320,200))
    #im.save("/s/attachment/" + file_name+"_thumbnail.jpg")
    imgext = re.search("(\.\w*)$", file_name)
    if imgext:
        thumbnail_name = file_name + "_thumbnail"+ imgext.group(1)
    else:                
        thumbnail_name = file_name + "_thumbnail.jpg"
    pureext = imgext.group(1)[1:]
    if pureext == "jpg":
        pureext = "jpeg"
    #bucket.put_object(thumbnail_name, im.tostring('jpeg', 'RGB'))
    bucket.put_object(thumbnail_name, im.tostring("jpeg", 'RGB'))
    thumbnail_url = bucket.generate_url(thumbnail_name)
    #s = sae.storage.Client()
    #ob = sae.storage.Object(data = data, cache_control='access plus %s day' % expires, content_type= type, content_encoding= encoding)
    return file_url, thumbnail_url
开发者ID:firsthym,项目名称:rebang,代码行数:33,代码来源:views.py

示例2: imgupload

# 需要导入模块: from sae.storage import Bucket [as 别名]
# 或者: from sae.storage.Bucket import generate_url [as 别名]
def imgupload(req):
	username = req.session.get("username",'')
	if username == '':
		return HttpResponseRedirect('/admin')
	else:
		if req.POST:
			post = req.POST
			if req.FILES:
				img = req.FILES['img']
				# s = Client()
				bucket = Bucket('img')
				# st = bucket.conn.__dict__
				# if bucket.stat()['bytes'] == '0':
				bucket.put()
				bucket.post(acl='.r:.sinaapp.com,.r:sae.sina.com.cn')
				tut = img._name.split('.')[-1]
				dt_str = datetime.strftime(datetime.now(),'%Y%m%d%H%M%S')
				filename = dt_str + str(randint(100,999)) + '.' + tut
				bucket.put_object(filename,img)
				# s.put('hitmstcweb',filename,img)
				image = Img(
							name = post.get('name','dt_str'), \
							descripe = post.get('descripe',''), \
							img = bucket.generate_url(filename), \
							author = User.objects.get(username = username), \
							)
				image.save()
	content = {'last_event':get_last_event()}
	return render_to_response('imgupload.html',content,context_instance = RequestContext(req));
开发者ID:HIT-MSTC,项目名称:mstc-website,代码行数:31,代码来源:views.py

示例3: post

# 需要导入模块: from sae.storage import Bucket [as 别名]
# 或者: from sae.storage.Bucket import generate_url [as 别名]
    def post(self, id):
        id = int(id)
        from sae.storage import Bucket

        bucket = Bucket('audio')
        fid = str(self.current_user) + datetime.now().strftime('/%Y-%m-%dT%H-%M-%S')
        name = fid + '.wav'
        #length = int(request.get_header('content-length',0))

        bucket.put_object(name, self.request.body)

        name = bucket.generate_url(name)

        sss = Session()
        model = RoomChat()
        model.room_id = id
        model.content_type = 'audio'
        model.content = name
        model.user_name = self.user.name
        model.user_id = self.current_user
        model.create_at = datetime.now()

        sss.add(model)
        sss.commit()

        ls = GetTop.ajax(id)
        self.render_list(*ls)
开发者ID:lusionx,项目名称:sae-lxpy-1,代码行数:29,代码来源:room.py

示例4: put_obj2storage

# 需要导入模块: from sae.storage import Bucket [as 别名]
# 或者: from sae.storage.Bucket import generate_url [as 别名]
def put_obj2storage(file_name="", data="", expires="365", type=None, encoding=None, domain_name=STORAGE_DOMAIN_NAME):
    whichStorage = int(getAttr("DEFAULT_STORAGE"))
    if whichStorage == 0:
        bucket = Bucket(domain_name)
        bucket.put_object(file_name, data, content_type=type, content_encoding=encoding)
        return bucket.generate_url(file_name)
    elif whichStorage == 1:
        import qiniu.conf, qiniu.rs, qiniu.io

        qiniu.conf.ACCESS_KEY = getAttr("QNKEY")
        qiniu.conf.SECRET_KEY = getAttr("QNSECRET")
        policy = qiniu.rs.PutPolicy(getAttr("QNSTORAGE"))
        uptoken = policy.token()
        key = file_name
        if key[0] == "/":
            key = key[1:]
        ret, err = qiniu.io.put(uptoken, key, data)
        if err is not None:
            print "err = ", err
            return ""
        ###下面返回的网址有可能不同,有的是 xxxx.u.qiniudn.com 请改为自己的
        return "http://%s/%s" % (getAttr("QNDOMAIN"), key)
    else:
        # 可后续扩展其他云存储
        pass
    return ""
开发者ID:yobin,项目名称:saepy-log,代码行数:28,代码来源:admin.py

示例5: save_with_bucket

# 需要导入模块: from sae.storage import Bucket [as 别名]
# 或者: from sae.storage.Bucket import generate_url [as 别名]
 def save_with_bucket(self, _bucket, fname, fcontent):
     '''
     _bucket is customer bucket name
     '''
     bk = Bucket(_bucket)
     import StringIO
     b = StringIO.StringIO(fcontent)
     bk.put_object(fname, b.read())
     return bk.generate_url(fname)
开发者ID:snowleung,项目名称:sae_init,代码行数:11,代码来源:StorageAdapter.py

示例6: submit_report

# 需要导入模块: from sae.storage import Bucket [as 别名]
# 或者: from sae.storage.Bucket import generate_url [as 别名]
def submit_report(req):
	username = req.session.get('username','')
	content = {'active_menu':'submitReport','num_need_check':num_need_check()}
	status = ''
	if username != '':
		user = MyUser.objects.get(user__username = username)
		content['user'] = user
	else:
		return HttpResponseRedirect('/login/')
	if req.POST:
		post = req.POST
		if req.FILES:
			img1 = req.FILES['img1']
			img2 = req.FILES['img2']
			bucket = Bucket('img')
			bucket.put()
			bucket.post(acl='.r:.sinaapp.com,.r:sae.sina.com.cn')
			tut1 = img1._name.split('.')[-1]
			tut2 = img2._name.split('.')[-1]
			if tut1.lower() not in ['jpg','jpeg','bmp','gif','png']:
				tut1 = 'jpg'
			if tut2.lower() not in ['jpg','jpeg','bmp','gif','png']:
				tut2 = 'jpg'
			dt_str = datetime.datetime.strftime(datetime.datetime.now(),'%Y%m%d%H%M%S')
			filename1 = dt_str + str(randint(100,999)) + '.' + tut1
			filename2 = dt_str + str(randint(100,999)) + '.' + tut2
			bucket.put_object(filename1,img1)
			bucket.put_object(filename2,img2)
		info = post.get('info','')
		if len(info) < 500:
			status = 'info_short'
		else:
			report = Report(
							name = post.get('name',''),
							start_time = post.get('start_time',''),
							end_time = post.get('end_time',''),
							address = post.get('address',''),
							status = 1,
							apply_time = 0,
							apply_score = 0,
							report_type = post.get('report_type',''),
							author_type = post.get('author_type',''),
							info_type = post.get('info_type',''),
							author = user,
							img1 = bucket.generate_url(filename1), \
							img2 = bucket.generate_url(filename2), \
							)
			if post.get('info_type','') == '2':
				a = re.compile(r'(<script)(.*)(>)',re.I)
				res = r'&lt;script\2&gt;'
				report.info = a.sub(res,info)
			else:
				report.info = info
			report.save()
			status = 'success'
		content['status'] = status
	return render_to_response('submitreport.html', content, context_instance = RequestContext(req))
开发者ID:yumendy,项目名称:shsj,代码行数:59,代码来源:views.py

示例7: save_img

# 需要导入模块: from sae.storage import Bucket [as 别名]
# 或者: from sae.storage.Bucket import generate_url [as 别名]
def save_img(uid,device_name,file1):
    filename = file1.name
    timestamp=filename.split(".")[0]
    url="www.baidu.com"
    if 'SERVER_SOFTWARE' in os.environ:
        bucket = Bucket('domain2')
        bucket.put_object(filename, file1)
        url = bucket.generate_url(filename)
    image=Img.create(uid=uid,timestamp=timestamp,device_name=device_name,url=url)
    image.save()
开发者ID:myang321,项目名称:FinderServer,代码行数:12,代码来源:utils.py

示例8: upload_storage

# 需要导入模块: from sae.storage import Bucket [as 别名]
# 或者: from sae.storage.Bucket import generate_url [as 别名]
def upload_storage(bucketname=BUCKET, savename="test.txt", filedata=None):
    if bucketname and savename and filedata:
        if DEBUG:
            return None
        from sae.storage import Bucket
        bucket = Bucket(bucketname)
        if savename[0]=="/":
            savename = savename[1:]
        bucket.put_object(savename, filedata)
        return bucket.generate_url(savename)
    else:
        return False
开发者ID:kerneltravel,项目名称:ijd8,代码行数:14,代码来源:views.py

示例9: store_image

# 需要导入模块: from sae.storage import Bucket [as 别名]
# 或者: from sae.storage.Bucket import generate_url [as 别名]
 def store_image(self):
     match = re.search(r'p[\d]+.jpg', self.douban.images)
     if match:
         image = urllib2.urlopen('http://img4.douban.com/view/photo/raw/public/' + match.group()).read()
     else:
         image = urllib2.urlopen(self.douban.images).read()
     from sae.storage import Bucket
     bucket = Bucket('infopic')
     bucket.put()
     filename = '%s.jpg' % self.id
     bucket.put_object(filename, image)
     url = bucket.generate_url(filename)
     self.images = url
     self.save()
开发者ID:akinoniku,项目名称:episodeget,代码行数:16,代码来源:models.py

示例10: save_image

# 需要导入模块: from sae.storage import Bucket [as 别名]
# 或者: from sae.storage.Bucket import generate_url [as 别名]
def save_image(con, file1, pid, is_front):
    if file1.filename == '':
        return
    # filename = str(pid) + '_' + get_random_number_str() + '_' + file1.filename
    ext = file1.filename.split('.')[-1]
    filename = str(pid) + get_random_number_str() + '.' + ext
    if 'SERVER_SOFTWARE' in os.environ:
        bucket = Bucket('domain1')
        bucket.put_object(filename, file1)
        url = bucket.generate_url(filename)
    else:
        url = filename
        file_full_path = os.path.join(UPLOAD_FOLDER, filename)
        if os.environ.get('USER') == 'Lily':
            file_full_path = "/Users/Lily/PycharmProjects/EIA/static/upload/" + filename
        file1.save(file_full_path)
    save_img_url(con, url, pid, 1 if is_front else 0)
开发者ID:myang321,项目名称:EIA,代码行数:19,代码来源:database_setup.py

示例11: _upload_image

# 需要导入模块: from sae.storage import Bucket [as 别名]
# 或者: from sae.storage.Bucket import generate_url [as 别名]
def _upload_image(request, field="cover"):
    if 'file' in request.FILES:
        fobj = request.FILES['file']
        content = fobj.read()
        suffix = fobj.name.rsplit('.', 1)[1].lower()
        if suffix not in ('jpg', 'png', 'jpeg'):
            return _error(u'请上传jpg或者png格式的照片')
        md5 = hashlib.md5(content).hexdigest()
        filename = '%s.%s' % (md5, suffix)

        from sae.storage import Bucket
        bucket = Bucket('adam')
        bucket.put()
        bucket.post(acl='.r:.sinaapp.com,.r:sae.sina.com.cn', metadata={'expires': '1y'})
        bucket.put_object(filename, content)
        return bucket.generate_url(filename)
    return request.POST.get(field, '').strip()[0:255]
开发者ID:merrycode,项目名称:red,代码行数:19,代码来源:views.py

示例12: POST

# 需要导入模块: from sae.storage import Bucket [as 别名]
# 或者: from sae.storage.Bucket import generate_url [as 别名]
 def POST(self):
     bucket = Bucket('backup')
     str_data = web.data() #获得post来的数据
     js = json.loads(str_data,"utf-8")
     if "passwd" in js.keys():
         if js["passwd"] != config.passwdDatas:
             return u"密码错误"
     else:
         return u"请求格式不正确"
     if "type" in js.keys():
         if "filename" in js.keys():
             stamp = kv.get("kvdatastamp")
             sha1=hashlib.sha1()
             sha1.update(stamp)
             sha1.update(config.keyUserRestore)
             hashcode=sha1.hexdigest()
             if not "hashcode" in js.keys():
                 return u"请求类型不正确"
             if hashcode != js["hashcode"]:
                 return u"验证失败"
             if js["type"] == "restore":
                 return ReadZipFile(js["filename"])
             elif js["type"] == "getfile":
                 return bucket.generate_url(js["filename"])
             else:
                 return u"请求类型不正确"
         elif js["type"] == "getfilelist":
             filelist = []
             stamp = str(int(time.time()))
             filelist.append(stamp)
             kv.set("kvdatastamp",stamp)
             for finf in bucket.list():
                 filelist.append(str(finf[u'name']))
             return ",".join(filelist)
         else:
             return u"请求格式不正确"
             
     else:
         return u"请求格式不正确"
开发者ID:zhangningningcn,项目名称:weixinsendmail,代码行数:41,代码来源:kvbackup.py

示例13: AvatarManager

# 需要导入模块: from sae.storage import Bucket [as 别名]
# 或者: from sae.storage.Bucket import generate_url [as 别名]
class AvatarManager(object):
    def __init__(self,app):
        self.app = app
        self.bucket = Bucket(app.config['STORAGE_NAME'])
        self.bucket.put()
        self.bucket.post(acl='.r:.sinaapp.com,.r:sae.sina.com.cn', metadata={'expires': '1d'})

    def _saveAvatar(self,file,filename,size,sizecode):
        filetype = file.mimetype.split('/')[1]
        img = Image.open(StringIO(file.read()))
        file.seek(0)
        ratio = float(img.size[0]) / img.size[1]
        if ratio > 1:
            length = int(img.size[1]/2)
        else:
            length = int(img.size[0]/2)
        x0,y0 = int(img.size[0]/2),int(img.size[1]/2)
        img = img.crop((x0-length,y0-length,x0+length,y0+length))
        img = img.resize((size,size),Image.ANTIALIAS)

        output = StringIO()
        img.save(output,filetype)
        content = output.getvalue()
        output.close()
        self.bucket.put_object('avatar/'+filename, content, content_type=file.mimetype)

    def saveAvatar(self,file,id):
        filename = str(id)
        self._saveAvatar(file,filename,self.app.config['AVATAR_SIZE_S'],'s')
        self._saveAvatar(file,filename,self.app.config['AVATAR_SIZE_M'],'m')
        self._saveAvatar(file,filename,self.app.config['AVATAR_SIZE_L'],'l')

    def getAvatarUrl(self,id,sizecode):
        try:
            self.bucket.stat_object('avatar/'+str(id)+sizecode)
        except :
            return self.app.config['DEFAULT_AVATAR_URL']+'/'+sizecode
        return self.bucket.generate_url('avatar/'+str(id)+sizecode)
开发者ID:eavae,项目名称:mlang,代码行数:40,代码来源:files.py

示例14: post

# 需要导入模块: from sae.storage import Bucket [as 别名]
# 或者: from sae.storage.Bucket import generate_url [as 别名]
    def post(self):

        msg = []
        from sae.storage import Bucket

        domain = 'ufiles'

        def dt0num(d=None):
            if d is None:
                d = datetime.now()
            dt0 = datetime(2010, 1, 1)
            return int((d - dt0).total_seconds())

        sss = Session()
        dbf = File(user_id=self.get_argument('uid'), domain=domain, create_at=datetime.now(), visible=1)
        sss.add(dbf)
        bucket = Bucket(domain)

        for f in self.request.files['Filedata']:

            fname, ext = os.path.splitext(f['filename'])

            dbf.path = self.get_argument('uid') + '/' + fname \
                + '.' + str(dt0num()) + ext

            bucket.put_object(dbf.path, f['body'])

            #url = bucket.generate_url(path)

            dbf.size = len(f['body'])

            sss.commit()

            msg.append(dict(name=f['filename'], len=len(f['body']), url=bucket.generate_url(dbf.path)))


        self.render_dict(code=200, uid=self.get_argument('uid', '-1'), msg=msg)
开发者ID:lusionx,项目名称:sae-lxpy-1,代码行数:39,代码来源:upload.py

示例15: report_edit

# 需要导入模块: from sae.storage import Bucket [as 别名]
# 或者: from sae.storage.Bucket import generate_url [as 别名]
def report_edit(req):
	username = req.session.get('username','')
	status = ''
	if username != '':
		user = MyUser.objects.get(user__username = username)
	else:
		return HttpResponseRedirect('/login/')
	Id = req.GET.get('id','')
	try:
		report = Report.objects.get(pk = Id)
	except:
		return HttpResponseRedirect('/reportlist/')
	if report.author != user:
		return HttpResponseRedirect('/reportlist/')
	else:
		if report.status != 1:
			status = 'cannot_edit'
		else:
			if req.POST:
				post = req.POST
				if req.FILES:
					img1 = req.FILES['img1']
					img2 = req.FILES['img2']
					bucket = Bucket('img')
					bucket.put()
					bucket.post(acl='.r:.sinaapp.com,.r:sae.sina.com.cn')
					tut1 = img1._name.split('.')[-1]
					tut2 = img2._name.split('.')[-1]
					if tut1.lower() not in ['jpg','jpeg','bmp','gif','png']:
						tut1 = 'jpg'
					if tut2.lower() not in ['jpg','jpeg','bmp','gif','png']:
						tut2 = 'jpg'
					dt_str = datetime.datetime.strftime(datetime.datetime.now(),'%Y%m%d%H%M%S')
					filename1 = dt_str + str(randint(100,999)) + '.' + tut1
					filename2 = dt_str + str(randint(100,999)) + '.' + tut2
					bucket.put_object(filename1,img1)
					bucket.put_object(filename2,img2)
				info = post.get('info','')
				if len(info) < 500:
					status = 'info_short'
				else:
					report.name = post.get('name','')
					report.start_time = post.get('start_time','')
					report.end_time = post.get('end_time','')
					report.address = post.get('address','')
					report.report_type = post.get('report_type','')
					report.author_type = post.get('author_type','')
					report.info_type = post.get('info_type','')
					try:
						img1 = bucket.generate_url(filename1)
						img2 = bucket.generate_url(filename2)
						report.img1 = img1
						report.img2 = img2
					except:
						pass
					if post.get('info_type','') == '2':
						a = re.compile(r'(<script)(.*)(>)',re.I)
						res = r'&lt;script\2&gt;'
						report.info = a.sub(res,info)
					else:
						report.info = info
					report.save()
					status = 'success'
	content = {'user':user,'active_menu':'submitReport','num_need_check':num_need_check(),'report':report, 'status':status}
	return render_to_response("report_edit.html",content,context_instance = RequestContext(req))
开发者ID:yumendy,项目名称:shsj,代码行数:67,代码来源:views.py


注:本文中的sae.storage.Bucket.generate_url方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。