def upload_image(image_data): """上传,保存图片到七牛云""" # 创建七牛云对象 q = qiniu.Auth(access_key, secret_key) # 获取上传的token token = q.upload_token(bucket_name) # 调用上传的方法,实现生产并响应结果给我们 # 说明:参数2传入None,表示让七牛云给我们生成数据的唯一标识key ret, info = qiniu.put_data(token, None, image_data) # 判断上传图片是否成功 if info.status_code == 200: key = ret.get('key') return key else: raise Exception('上传图片失败') # print 'ret:', ret # print 'info:', info # if ret is not None: # print 'all is ok' # else: # print info # if __name__ == '__main__': # path = '/home/python/PycharmProjects/iHome/fruit.jpg' # with open(path, 'rb') as f: # image_data = f.read() # upload_image(image_data)
def upload(request): q = qiniu.Auth(settings.QINIU_ACCESS_KEY, settings.QINIU_SECRET_KEY) token = q.upload_token('brandicon') import requests, sys, io brand_icons = list( Carbrand.objects.filter(brandicon__isnull=False).values_list( 'brandicon', flat=True)) print(len(brand_icons)) i = 0 for item in brand_icons: print('开始抓取第{0}条'.format(i)) result = requests.get('http://easy.jy-epc.com/icons/brand_icons/' + item) file = io.BytesIO(result.content) res, info = qiniu.put_stream(token, item, file, 'test', len(result.content)) print(res, info) if not res: print('上传失败!') i = i + 1 return HttpResponse('success')
def pic_storage(data): """将图片二进制数据上传到七牛云""" # 用户权限鉴定 q = qiniu.Auth(access_key, secret_key) # 图片名称 ,如果不指明七牛云会自动生成一个随机的唯一的图片名称 # key = 'hello' token = q.upload_token(bucket_name) if not data: return AttributeError("图片数据为空") try: # 将二进制图片数据上传到七牛云(网络请求有可能失败) ret, info = qiniu.put_data(token, None, data) except Exception as e: current_app.logger.error(e) raise e print(ret) print("---------") print(info) # 工具类如果产生异常千万别私自处理,应该抛出,方便调用者查询异常所在。 if info.status_code != 200: raise Exception("图片上传到七牛云失败") # 返回图片名称 return ret["key"]
def pic_storage(data): """借助七牛云上传图片""" # 身份鉴定 q = qiniu.Auth(access_key, secret_key) # 上传的图片名称, 如果不指明,七牛云会给你分配一个唯一的图片名称 # key = 'hello' if not data: return None token = q.upload_token(bucket_name) try: # 调用七牛云sdk上传二进制图片数据 ret, info = qiniu.put_data(token, None, data) except Exception as e: # 自定义工具方法的异常一定要抛出给调用者,不能私自解决 raise e # print(ret) # print("--------") # print(info) if info.status_code != 200: # 上传图片到七牛云失败 raise Exception("上传图片到七牛云失败") # 上传图片成功 返回图片名称 return ret["key"]
def get(self, request): q = qiniu.Auth(QiniuConfig.ACCESS_KEY, QiniuConfig.SECRET_KEY) token = q.upload_token(QiniuConfig.BUCKET_NAME) return Response({ 'code': 0, 'upload_token': token, })
def video_file_upload(): if request.method == 'POST': times = time.strftime("%Y%m%d-%H%M%S", time.localtime()) uid = str(random.randint(1000, 9999)) # str用于把数字转换成字符串 uid = times + uid # # 需要填写你的 Access Key 和 Secret Key access_key = 'SvHVcX7ZotlGtp7Lpxy1Az95Ae_tC8lOqnC02A9C' secret_key = 'blSArZE6UCrYABtjaYwTFLHeBXCeofUKjpoEKspi' # 验证 q = qiniu.Auth(access_key, secret_key) # 储存空间名字 bucket = "fa" token = q.upload_token(bucket) data = { 'status': 200, 'message': 'ok', 'info': { 'token': token, 'key': 'video'+uid } } data = json.dumps(data, default=lambda o: o.__dict__) return data, 200, {"ContentType": "application/json"}
def uptoken(): AK = 'a3KafHAOJy_WPOuoV8dqTT4VvMWuhq9QNAFzD7tx' SK = 'W8lA713_lha9rt9mX4its0WWAPTWJWC4LiDcY8Yg' q = qiniu.Auth(AK, SK) bucket = 'jackie-cheng' token = q.upload_token(bucket) return jsonify({'uptoken': token})
def uptoken(): access_key = 'o4FRYaXOdV54Tok_yjD01AsSrGcRTEClCuxIsPro' secret_key = 'UOX3tkgoZ0f7cZL8DXJUjrsa0UkwjX_KRRsUk1jk' q = qiniu.Auth(access_key, secret_key) bucket_name = 'danibbs' token = q.upload_token(bucket_name) return jsonify({"uptoken": token})
def qiniu_token(key): try: q = qiniu.Auth(ACCESS_KEY, SECRET_KEY) token = q.upload_token(QINIU_BUCKET, key) except: return None return token
def get(self, request): access_key = settings.QINIU_ACCESS_KEY secret_key = settings.QINIU_SECRET_KEY q = qiniu.Auth(access_key, secret_key) bucket = settings.QINIU_BUCKET_NAME token = q.upload_token(bucket) return restful.result(data={'token': token})
def vsample(bucket, key, picFormat, startSecond, duration, pattern, resolution=None, rotate=None, interval=None): #准备命令 cmd = "vsample" #组织参数 cmdParams = { "ss": startSecond, "t": duration, "pattern": pattern, } if resolution: cmdParams.update({"s": resolution}) if rotate: cmdParams.update({"rotate": rotate}) if interval: cmdParams.update({"interval": interval}) #执行fop fop = qiniu.build_op(cmd, picFormat, **cmdParams) #默认为空,表示使用公共队列 usePipeline = "" #fop处理结果通知url notifyUrl = None auth = qiniu.Auth(accessKey, secretKey) pfop = qiniu.PersistentFop(auth, bucket, usePipeline, notifyUrl) retData, respInfo = pfop.execute(key, [fop], force=None) if retData != None: print("PersistentId:" + retData["persistentId"]) else: print("Error:") print("--StatusCode:" + str(respInfo.status_code)) print("--Reqid:" + respInfo.req_id) print("--Message:" + respInfo.error)
def setup_qiniu(qiniu_config): import qiniu from util.qiniu_util import QiniuUtil QiniuUtil.BucketName = qiniu_config['bucket_name'] QiniuUtil.BucketUrl = qiniu_config['bucket_url'] QiniuUtil.Auth = qiniu.Auth(access_key=qiniu_config['access_key'], secret_key=qiniu_config['access_secret'])
def getToken(self, file_name): q = qiniu.Auth(QINIU_ACCESS_KEY, QINIU_SECRET_KEY) # key = file_name key = file_name # token = q.upload_token(QINIU_BUCKET_NAME,key = key ,policy = {"insertOnly": 0},) token = q.upload_token(QINIU_BUCKET_NAME, key=key) return token
def post(self, request, *args, **kwargs): data = request.FILES.get('data') # f = open(data, 'r') # print(data) # print(request.FILES) # print(requet.) access_key = settings.QINIU_ACCESS_KEY secret_key = settings.QINIU_SECRET_KEY # 设置七牛空间(自己刚刚创建的) bucket_name = settings.QINIU_BUCKET_NAME # 构建鉴权对象,授权 q = qiniu.Auth(access_key, secret_key) key = str(request.data.get('filename')) + '.png' print(request.data.get('filename')) # 生成token token = q.upload_token(bucket_name, key, 3600) print(token) # 返回token,key必须为uptoken ret, info = put_data(token, key, data.read()) print(info, ret) # print(info.status_code) # if info.status_code == 200: # url = settings.QINIU_BUCKET_DOMAIN + key # return url avatar_url = settings.QINIU_BUCKET_DOMAIN + key return JsonResponse({"uptoken": token, "avatar_url": avatar_url})
def UploadToken(request): access_key = '2zdV4opbmFZaDcTF0yUfW25kymJrpWNpx3MtkUwM' secret_key = '2fw3FgmHRaoYdSyUca8A3clQKiowHDiL4FsusSEC' q = qiniu.Auth(access_key, secret_key) bucket = 'item-list' token = q.upload_token(bucket) return JsonResponse({'uptoken': token})
def uptoken(): access_key = "RGJIrhTPY74Wo4SZw8OTzSnxTvLIu6lbPzrTu2xr" secret_key = "j6AbvPSo8tFsNu6Hwoh9X2wyFGHjUvNNswkUq00t" q = qiniu.Auth(access_key, secret_key) bucket = "mybaobao" token = q.upload_token(bucket) return jsonify({"uptoken": token})
def article_image_upload(request): '''图片上传''' obj = request.FILES.get("upload_img") path = os.path.join(settings.MEDIA_ROOT, "article_img", obj.name) with open(path, "wb") as f: for line in obj: f.write(line) access_key = settings.QINIU_ACCESS_KEY secret_key = settings.QINIU_SECRET_KEY q = qiniu.Auth(access_key, secret_key) bucket = settings.QINIU_BUCKET_NAME token = q.upload_token(bucket) ret, info = put_file(token, None, path) if info.status_code == 200: # 表示上传成功, 返回文件名 res = { "error": 0, "url": "http://py9v5zj1h.bkt.clouddn.com"+"/"+ret["key"] } else: # 上传七牛失败 使用本地的上传图片 res = { "error": 0, "url": "/media/article_img/" + obj.name } return JsonResponse(res)
def upload_to_qiniu(localfile, clean_localfile=True): """ 上传一个本地文件到七牛,返回文件的file_key,同时默认删除本地文件 ref: http://developer.qiniu.com/docs/v6/sdk/python-sdk.html#upload-do """ auth = qiniu.Auth(QINIU_ACCESS_KEY, QINIU_SECRET_KEY) file_key = get_md5("%s%s" % ("web_auth-%d" % 1,\ datetime.datetime.now())) uptoken = auth.upload_token(bucket=QINIU_BUCKET_PUBLIC) mime_type = "text/plain" # 二进制流 "application/octet-stream" ret, info = qiniu.put_file(uptoken, file_key, localfile, mime_type=mime_type) if ret is not None: if clean_localfile: # 默认上传成功会删除本地文件 os.remove(localfile) return file_key else: # print(info) # error message in info return None
def vframe(format, offset, width, height, rotate, fromBucket, fromKey, usePipeline="", notifyUrl=None, saveBucket=None, saveKey=None): #prepare fop params = {"offset": offset, "w": width, "h": height, "rotate": rotate} fop = qiniu.build_op("vframe", format, **params) if saveBucket != None and saveKey != None: fop = qiniu.op_save(fop, saveBucket, saveKey) #do pfop auth = qiniu.Auth(accessKey, secretKey) pfop = qiniu.PersistentFop(auth, fromBucket, usePipeline, notifyUrl) retData, respInfo = pfop.execute(fromKey, [fop], force=None) if retData != None: print("PersistentId:" + retData["persistentId"]) else: print("Error:") print("--StatusCode:" + str(respInfo.status_code)) print("--Reqid:" + respInfo.req_id) print("--Message:" + respInfo.error)
def uptoken(): ACCESS_KEY = 'W2ydQ1qDpNZpzJG1SaseiTrgdjpIPNhZ3hfR3cVN' SECRET_KEY = 'oGG5ocZ9UP66gANQh0eZk9I2odKu1iN9iyGQdKcW' q = qiniu.Auth(ACCESS_KEY, SECRET_KEY) bucket = 'flask-blog' token = q.upload_token(bucket) return jsonify({'uptoken': token})
def __init__(self, access, secret): self.access_key = access self.secret_key = secret self._q = qiniu.Auth(self.access_key, self.secret_key) self._bucket = qiniu.BucketManager(self._q) self.mcu_url = None self.file_list_size = 10
def upload_image(image_data): # 创建七牛云对象 q = qiniu.Auth(access_key, secret_key) # 获取上传的token token = q.upload_token(bucket_name) # 调用上传的方法,实现生产并响应结果给我们 # 说明:参数2传入None,表示让七牛云给我们生成数据的唯一标识key ret, info = qiniu.put_data(token, None, image_data) # 判断上传图片是否成功 if info.status_code == 200: key = ret.get('key') return key else: raise Exception('上传图片失败') # print 'RET' ,ret # print 'INFO' , info # if __name__ == '__main__': # path = '/home/python/Desktop/微信图片_20180327181731.jpg' # with open(path,'rb') as file: # image_data = file.read() # upload_image(image_data)
def uptoken(): access_key = '7wL2HnNizlF2OCeFGkmu2KdMG0exOXsA5GQi8EMT' secrect_key = 'fYQ30QziTfynz-osSuoq6pA7xewupEy764l6Zxgl' q = qiniu.Auth(access_key, secrect_key) bucket = 'images' token = q.upload_token(bucket) return jsonify({'uptoken': token})
def query(persistentId): #print(persistentId) auth = qiniu.Auth(accessKey, secretKey) url = 'http://{0}/status/get/prefop?id={1}'.format(config.API_HOST, persistentId) retData, respInfo = http._get(url, params=None, auth=auth) if retData != None: print("Success: (" + persistentId + ")") print("---id:" + retData["id"]) print("---code:" + str(retData["code"])) print("---desc:" + retData["desc"]) for item in retData["items"]: print("---cmd:" + item["cmd"]) print("------code:" + str(item["code"])) print("------desc:" + item["desc"]) if item.__contains__("error"): print("------error:" + item["error"]) if item.__contains__("hash"): print("------hash:" + item["hash"]) if item.__contains__("key"): print("------key:" + item["key"]) else: #print(respInfo) print("Error (" + persistentId + "):") print("--StatusCode:" + str(respInfo.status_code)) print("--Reqid:" + respInfo.req_id) print("--Message:" + respInfo.error) print("\r\n")
def uptoken(): access_key = '' secret_key = '' q = qiniu.Auth(access_key, secret_key) bucket = '' token = q.upload_token(bucket) return jsonify({"uptoken": token})
def __init__(self, acces_key, secret_key, bucket): # 1-1: 构建权限对象 self.q = qiniu.Auth(acces_key, secret_key) # 1-2: 生成token: 300秒有效 self.token = self.q.upload_token(bucket, None, 300) self.bucket = bucket self.bucket_api = qiniu.BucketManager(self.q)
def uptoken(): access_key = "#" secret_key = "#" q = qiniu.Auth(access_key, secret_key) bucket = "存储空间名字" token = q.upload_token(bucket) return jsonify({"uptoken": token})
def uploadData(data): if type(data) == QByteArray: data = data.data() from .secfg import qiniu_acckey, qiniu_seckey, qiniu_bucket_name access_key = qiniu_acckey secret_key = qiniu_seckey bucket_name = qiniu_bucket_name print(access_key, secret_key, bucket_name) q = qiniu.Auth(access_key, secret_key) # 由于本机时间错误,导致计算了出的token立即失效: # text_body:{"error":"expired token"} token = q.upload_token(bucket_name, expires=3600*24) key = 'helloqt.png' key = FileStore.md5sum(data) # data = 'hello qiniu!' # data = load_from_file(PATH) print('uploading file:', key, token) ret, info = qiniu.put_data(token, key, data) if ret is not None: print('upload file All is OK', ret) url = 'http://7xn2rb.com1.z0.glb.clouddn.com/%s' % key return url else: print(ret, '=====', info) # error message in info return str(info)
def qiniu_oper(request, oper_type): response = Response.ResponseObj() if oper_type == 'get_token': SecretKey = 'wVig2MgDzTmN_YqnL-hxVd6ErnFhrWYgoATFhccu' AccessKey = 'a1CqK8BZm94zbDoOrIyDlD7_w7O8PqJdBHK-cOzz' q = qiniu.Auth(AccessKey, SecretKey) bucket_name = 'bjhzkq_tianyan' token = q.upload_token(bucket_name) # 可以指定key 图片名称 response.code = 200 response.msg = '生成成功' response.data = {'token': token} elif oper_type == 'test_article': objs = models.Goods.objects.all() for obj in objs: print('obj.id--> ', obj.id, obj.goods_describe) goods_describe = [] for i in json.loads(obj.goods_describe): status = i.get('status') content = i.get('content') if status == 'img' and 'http://tianyan.zhugeyingxiao.com' not in content: path = requests_img_download(content) img = update_qiniu(path) goods_describe.append({ 'status': status, 'content': img, }) else: goods_describe.append(i) obj.goods_describe = goods_describe obj.save() return JsonResponse(response.__dict__)
def upload_ssl(self): session = requests.Session() auth = qiniu.Auth(access_key=self.access_key, secret_key=self.secret_key) url = "https://{}{}".format(self.HOST, "/sslcert") token = auth.token_of_request(url) headers = { "Authorization": 'QBox {0}'.format(token), "Content-Type": "application/json", "Host": self.HOST, } self._get_ssl() resp = session.post(url, json={ "name": "ssl{}new".format(time.strftime('%Y%m%d', time.localtime())), "common_name": self.root_domain, "ca": self.cert, "pri": self.cert_key, }, headers=headers) if resp.status_code != 200: return "", False cert_id = resp.json().get("certID", "") code = resp.json().get("code", 0) if cert_id and code == 200: return cert_id, True return resp.content, False