def get_auth(): return Auth(qiniu_auth['access_key'], qiniu_auth['secret_key'])
def uptoken(request): q = Auth(ACCESS_KEY, SECRET_KEY) token = q.upload_token(BUCKET_NAME) data = {'uptoken': token} return HttpResponse(json.dumps(data), content_type="application/json")
def move_file( username, path, filename, newpath, newfilename, bucket=None ): # bucket即bucketmanager path='/dir/dir' 可用于重命名文件,移动文件,移动目录,重命名目录 # ok user = User.objects.filter(username=username) if bool(user): user = user[0] else: return False if bucket == None: q = Auth(settings.QINIU_ACCESS_KEY, settings.QINIU_SECRET_KEY) # 授权 bucket = BucketManager(q) if not check_str(filename) or not check_str( path, ispath=True) or not check_str(newfilename) or not check_str( newpath, ispath=True): return False file1 = FileInfo.objects.filter(owner=user, file_name=filename, file_path=path) filecheck = FileInfo.objects.filter( owner=user, file_path=newpath) # filepath 可以不存在 if bool(file1) and bool(filecheck): update_dir_size(username, path, 0 - file1[0].size) update_dir_size(username, newpath, file1[0].size) else: return False # 数据库操作 file1 = FileInfo.objects.filter(owner=user, file_name=filename, file_path=path) if bool(file1): file1 = file1[0] else: return False # 文件名或者文件夹名不存在 filecheck = FileInfo.objects.filter(owner=user, file_name=newfilename, file_path=newpath) if bool(filecheck): return False file1.file_path = newpath file1.file_name = newfilename file1.save() if path == '/': path = '' if newpath == '/': newpath = '' if file1.file_type == 'dir': subpath = ''.join([path, '/', filename]) files = FileInfo.objects.filter(owner=user, file_path=subpath) subpath2 = ''.join([newpath, '/', newfilename]) for f in files: if f.file_type != 'dir': f.file_path = subpath2 f.save() key = ''.join([username, subpath, '/', f.file_name]) key2 = ''.join([username, subpath2, '/', f.file_name]) ret, info = bucket.move(settings.QINIU_BUCKET_NAME, key, settings.QINIU_BUCKET_NAME, key2) print info # assert ret=={} else: move_file(username, subpath, f.file_name, subpath2, f.file_name, bucket) else: key = ''.join([username, path, '/', filename]) key2 = ''.join([username, newpath, '/', newfilename]) ret, info = bucket.move(settings.QINIU_BUCKET_NAME, key, settings.QINIU_BUCKET_NAME, key2) print info # assert ret == {} return True
from qiniu import Auth, put_file from config import * import requests cover_url = "http://{qiniu_domain}/{key}?imageMogr2/thumbnail/1000x/crop/x562" qiniu = Auth(qiniu_accesskey, qiniu_secretkey) bucket = qiniu_bucket header = { 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36' } def qiniu_upload(local, key): token = qiniu.upload_token(bucket, key, 3600) ret, info = put_file(token, key, local) pic = requests.get(cover_url.format(qiniu_domain=qiniu_domain, key=key), headers=header) return pic.content
def qiniu_token(): q = Auth(QINIU_AK, QINIU_SK) return q.upload_token(BUCKET, expires=3600)
class UploaderTestCase(unittest.TestCase): mime_type = "text/plain" params = {'x:a': 'a'} q = Auth(access_key, secret_key) def test_put(self): key = 'a\\b\\c"hello' data = 'hello bubby!' token = self.q.upload_token(bucket_name) ret, info = put_data(token, key, data) print(info) assert ret['key'] == key def test_put_crc(self): key = '' data = 'hello bubby!' token = self.q.upload_token(bucket_name, key) ret, info = put_data(token, key, data, check_crc=True) print(info) assert ret['key'] == key def test_putfile(self): localfile = __file__ key = 'test_file' token = self.q.upload_token(bucket_name, key) ret, info = put_file(token, key, localfile, mime_type=self.mime_type, check_crc=True) print(info) assert ret['key'] == key assert ret['hash'] == etag(localfile) def test_putInvalidCrc(self): key = 'test_invalid' data = 'hello bubby!' crc32 = 'wrong crc32' token = self.q.upload_token(bucket_name) ret, info = _form_put(token, key, data, None, None, crc=crc32) print(info) assert ret is None assert info.status_code == 400 def test_putWithoutKey(self): key = None data = 'hello bubby!' token = self.q.upload_token(bucket_name) ret, info = put_data(token, key, data) print(info) assert ret['hash'] == ret['key'] data = 'hello bubby!' token = self.q.upload_token(bucket_name, 'nokey2') ret, info = put_data(token, None, data) print(info) assert ret is None assert info.status_code == 403 # key not match def test_withoutRead_withoutSeek_retry(self): key = 'retry' data = 'hello retry!' set_default(default_zone=Zone('http://a', 'http://upload.qiniu.com')) token = self.q.upload_token(bucket_name) ret, info = put_data(token, key, data) print(info) assert ret['key'] == key assert ret['hash'] == 'FlYu0iBR1WpvYi4whKXiBuQpyLLk' def test_putData_without_fname(self): if is_travis(): return localfile = create_temp_file(30 * 1024 * 1024) key = 'test_putData_without_fname' with open(localfile, 'rb') as input_stream: token = self.q.upload_token(bucket_name) ret, info = put_data(token, key, input_stream) print(info) assert ret is not None def test_putData_without_fname1(self): if is_travis(): return localfile = create_temp_file(30 * 1024 * 1024) key = 'test_putData_without_fname1' with open(localfile, 'rb') as input_stream: token = self.q.upload_token(bucket_name) ret, info = put_data(token, key, input_stream, self.params, self.mime_type, False, None, "") print(info) assert ret is not None def test_putData_without_fname2(self): if is_travis(): return localfile = create_temp_file(30 * 1024 * 1024) key = 'test_putData_without_fname2' with open(localfile, 'rb') as input_stream: token = self.q.upload_token(bucket_name) ret, info = put_data(token, key, input_stream, self.params, self.mime_type, False, None, " ") print(info) assert ret is not None
def __init__(self, config={}): self.auth = Auth(config['accessKey'], config['secretKey']) self.name = config['bucketName'] self.__getToken(self.name)
def __init__(self, accesskey, secretkey, bucketname, domain): self.option = "qiniu" self.bucketname = bucketname CommonYun.__init__(self, domain) self.qiniu = Auth(accesskey, secretkey) # 七牛认证 self.Bucket_Manager = BucketManager(self.qiniu) # 初始化BucketManager
def setUp(self): self.q = Auth(os.getenv('QINIUAK'), os.getenv('QINIUSK'))
class UploaderTestCase(unittest.TestCase): mime_type = "text/plain" params = {'x:a': 'a'} q = Auth(access_key, secret_key) def test_put(self): key = 'a\\b\\c"你好' data = 'hello bubby!' token = self.q.upload_token(bucket_name) ret, info = put_data(token, key, data) print(info) assert ret['key'] == key key = '' data = 'hello bubby!' token = self.q.upload_token(bucket_name, key) ret, info = put_data(token, key, data, check_crc=True) print(info) assert ret['key'] == key def test_putfile(self): localfile = __file__ key = 'test_file' token = self.q.upload_token(bucket_name, key) ret, info = put_file(token, key, localfile, mime_type=self.mime_type, check_crc=True) print(info) assert ret['key'] == key assert ret['hash'] == etag(localfile) def test_putInvalidCrc(self): key = 'test_invalid' data = 'hello bubby!' crc32 = 'wrong crc32' token = self.q.upload_token(bucket_name) ret, info = _form_put(token, key, data, None, None, crc=crc32) print(info) assert ret is None assert info.status_code == 400 def test_putWithoutKey(self): key = None data = 'hello bubby!' token = self.q.upload_token(bucket_name) ret, info = put_data(token, key, data) print(info) assert ret['hash'] == ret['key'] data = 'hello bubby!' token = self.q.upload_token(bucket_name, 'nokey2') ret, info = put_data(token, None, data) print(info) assert ret is None assert info.status_code == 403 # key not match def test_withoutRead_withoutSeek_retry(self): key = 'retry' data = 'hello retry!' set_default(default_zone=Zone('a', 'upload.qiniu.com')) token = self.q.upload_token(bucket_name) ret, info = put_data(token, key, data) print(info) assert ret['key'] == key assert ret['hash'] == 'FlYu0iBR1WpvYi4whKXiBuQpyLLk' qiniu.set_default(default_zone=qiniu.config.zone0) def test_hasRead_hasSeek_retry(self): key = 'withReadAndSeek_retry' data = StringIO('hello retry again!') set_default(default_zone=Zone('a', 'upload.qiniu.com')) token = self.q.upload_token(bucket_name) ret, info = put_data(token, key, data) print(info) assert ret['key'] == key assert ret['hash'] == 'FuEbdt6JP2BqwQJi7PezYhmuVYOo' qiniu.set_default(default_zone=qiniu.config.zone0) def test_hasRead_withoutSeek_retry(self): key = 'withReadAndWithoutSeek_retry' data = ReadWithoutSeek('I only have read attribute!') set_default(default_zone=Zone('a', 'upload.qiniu.com')) token = self.q.upload_token(bucket_name) ret, info = put_data(token, key, data) print(info) assert ret is None qiniu.set_default(default_zone=qiniu.config.zone0) def test_hasRead_WithoutSeek_retry2(self): key = 'withReadAndWithoutSeek_retry2' data = urlopen("http://www.qiniu.com") set_default(default_zone=Zone('a', 'upload.qiniu.com')) token = self.q.upload_token(bucket_name) ret, info = put_data(token, key, data) print(info) assert ret is None qiniu.set_default(default_zone=qiniu.config.zone0)
def __init__(self, access_key: str, secret_key: str, bucket: str, domain: str): self.auth = Auth(access_key, secret_key) self.bucket = bucket self.domain = domain
from qiniu import Auth, BucketManager AK = Your_AK SK = Your_SK q = Auth(AK, SK) c = BucketManager(q) info = c.buckets() print(info)
fb_retweet_dict = {'1':fb_retweet_1,'2':fb_retweet_2} tw_retweet_dict = {'1':tw_retweet_1,'2':tw_retweet_2} #use to save retweet/be_retweet retweet_r_1 = _default_redis_v2(host=RETWEET_REDIS_HOST,port=RETWEET_REDIS_PORT, db=1) retweet_r_2 = _default_redis_v2(host=RETWEET_REDIS_HOST, port=RETWEET_REDIS_PORT, db=2) retweet_redis_dict = {'1':retweet_r_1, '2':retweet_r_2} #use to save comment/be_comment comment_r_1 = _default_redis_v2(host=COMMENT_REDIS_HOST, port=COMMENT_REDIS_PORT, db=1) comment_r_2 = _default_redis_v2(host=COMMENT_REDIS_HOST, port=COMMENT_REDIS_PORT, db=2) comment_redis_dict = {'1':comment_r_1, '2':comment_r_2} #微信虚拟人相关 r_wx = _default_redis(host=REDIS_WX_HOST, port=REDIS_WX_PORT) qiniu = Auth(qiniu_access_key, qiniu_secret_key) #R_OPERATE_QUEUE = redis.StrictRedis(host=REDIS_CLUSTER_HOST_FLOW2, port=REDIS_CLUSTER_PORT_FLOW2, db=3) R_OPERATE_QUEUE = redis.StrictRedis(host=REDIS_HOST_45, port=REDIS_PORT_45, db=3) operate_queue_name = 'operate' #各类虚拟人从redis中获取编号时所对应的key fb_xnr_max_no = 'fb_xnr_max_no' tw_xnr_max_no = 'tw_xnr_max_no' wx_xnr_max_no = 'wx_xnr_max_no' wb_xnr_max_no = 'wb_xnr_max_no' qq_xnr_max_no = 'qq_xnr_max_no'
def private_url(base_url: str, duration_sec: int = URL_DURATION): q = Auth(Facade.config["qiniu"]["access_key"], Facade.config["qiniu"]["secret_key"]) return q.private_download_url(base_url, expires=duration_sec)
StringIO = StringIO.StringIO urlopen = urllib.urlopen elif is_py3: import io import urllib StringIO = io.StringIO urlopen = urllib.request.urlopen access_key = os.getenv('QINIU_ACCESS_KEY') secret_key = os.getenv('QINIU_SECRET_KEY') bucket_name = os.getenv('QINIU_TEST_BUCKET') dummy_access_key = 'abcdefghklmnopq' dummy_secret_key = '1234567890' dummy_auth = Auth(dummy_access_key, dummy_secret_key) def rand_string(length): lib = string.ascii_uppercase return ''.join([random.choice(lib) for i in range(0, length)]) def create_temp_file(size): t = tempfile.mktemp() f = open(t, 'wb') f.seek(size - 1) f.write(b('0')) f.close() return t
def test_nokey(self): with self.assertRaises(ValueError): Auth(None, None).token('nokey') with self.assertRaises(ValueError): Auth('', '').token('nokey')
class BucketTestCase(unittest.TestCase): q = Auth(access_key, secret_key) bucket = BucketManager(q) def test_list(self): ret, eof, info = self.bucket.list(bucket_name, limit=4) print(info) assert eof is False assert len(ret.get('items')) == 4 ret, eof, info = self.bucket.list(bucket_name, limit=1000) print(info) assert eof is True def test_buckets(self): ret, info = self.bucket.buckets() print(info) assert bucket_name in ret def test_prefetch(self): ret, info = self.bucket.prefetch(bucket_name, 'python-sdk.html') print(info) assert ret['key'] == 'python-sdk.html' def test_fetch(self): ret, info = self.bucket.fetch( 'http://developer.qiniu.com/docs/v6/sdk/python-sdk.html', bucket_name, 'fetch.html') print(info) assert ret['key'] == 'fetch.html' assert 'hash' in ret def test_fetch_without_key(self): ret, info = self.bucket.fetch( 'http://developer.qiniu.com/docs/v6/sdk/python-sdk.html', bucket_name) print(info) assert ret['key'] == ret['hash'] assert 'hash' in ret def test_stat(self): ret, info = self.bucket.stat(bucket_name, 'python-sdk.html') print(info) assert 'hash' in ret def test_delete(self): ret, info = self.bucket.delete(bucket_name, 'del') print(info) assert ret is None assert info.status_code == 612 def test_rename(self): key = 'renameto' + rand_string(8) self.bucket.copy(bucket_name, 'copyfrom', bucket_name, key) key2 = key + 'move' ret, info = self.bucket.rename(bucket_name, key, key2) print(info) assert ret == {} ret, info = self.bucket.delete(bucket_name, key2) print(info) assert ret == {} def test_copy(self): key = 'copyto' + rand_string(8) ret, info = self.bucket.copy(bucket_name, 'copyfrom', bucket_name, key) print(info) assert ret == {} ret, info = self.bucket.delete(bucket_name, key) print(info) assert ret == {} def test_change_mime(self): ret, info = self.bucket.change_mime(bucket_name, 'python-sdk.html', 'text/html') print(info) assert ret == {} def test_change_type(self): target_key = 'copyto' + rand_string(8) self.bucket.copy(bucket_name, 'copyfrom', bucket_name, target_key) ret, info = self.bucket.change_type(bucket_name, target_key, 1) print(info) assert ret == {} ret, info = self.bucket.stat(bucket_name, target_key) print(info) assert 'type' in ret self.bucket.delete(bucket_name, target_key) def test_copy_force(self): ret, info = self.bucket.copy(bucket_name, 'copyfrom', bucket_name, 'copyfrom', force='true') print(info) assert info.status_code == 200 def test_batch_copy(self): key = 'copyto' + rand_string(8) ops = build_batch_copy(bucket_name, {'copyfrom': key}, bucket_name) ret, info = self.bucket.batch(ops) print(info) assert ret[0]['code'] == 200 ops = build_batch_delete(bucket_name, [key]) ret, info = self.bucket.batch(ops) print(info) assert ret[0]['code'] == 200 def test_batch_copy_force(self): ops = build_batch_copy(bucket_name, {'copyfrom': 'copyfrom'}, bucket_name, force='true') ret, info = self.bucket.batch(ops) print(info) assert ret[0]['code'] == 200 def test_batch_move(self): key = 'moveto' + rand_string(8) self.bucket.copy(bucket_name, 'copyfrom', bucket_name, key) key2 = key + 'move' ops = build_batch_move(bucket_name, {key: key2}, bucket_name) ret, info = self.bucket.batch(ops) print(info) assert ret[0]['code'] == 200 ret, info = self.bucket.delete(bucket_name, key2) print(info) assert ret == {} def test_batch_move_force(self): ret, info = self.bucket.copy(bucket_name, 'copyfrom', bucket_name, 'copyfrom', force='true') print(info) assert info.status_code == 200 ops = build_batch_move(bucket_name, {'copyfrom': 'copyfrom'}, bucket_name, force='true') ret, info = self.bucket.batch(ops) print(info) assert ret[0]['code'] == 200 def test_batch_rename(self): key = 'rename' + rand_string(8) self.bucket.copy(bucket_name, 'copyfrom', bucket_name, key) key2 = key + 'rename' ops = build_batch_move(bucket_name, {key: key2}, bucket_name) ret, info = self.bucket.batch(ops) print(info) assert ret[0]['code'] == 200 ret, info = self.bucket.delete(bucket_name, key2) print(info) assert ret == {} def test_batch_rename_force(self): ret, info = self.bucket.rename(bucket_name, 'copyfrom', 'copyfrom', force='true') print(info) assert info.status_code == 200 ops = build_batch_rename(bucket_name, {'copyfrom': 'copyfrom'}, force='true') ret, info = self.bucket.batch(ops) print(info) assert ret[0]['code'] == 200 def test_batch_stat(self): ops = build_batch_stat(bucket_name, ['python-sdk.html']) ret, info = self.bucket.batch(ops) print(info) assert ret[0]['code'] == 200 def test_delete_after_days(self): days = '5' ret, info = self.bucket.delete_after_days(bucket_name, 'invaild.html', days) assert info.status_code == 612 key = 'copyto' + rand_string(8) ret, info = self.bucket.copy(bucket_name, 'copyfrom', bucket_name, key) ret, info = self.bucket.delete_after_days(bucket_name, key, days) assert info.status_code == 200
""" AUTHOR: zeng_xiao_yu GITHUB: https://github.com/zengxiaolou EMAIL: [email protected] TIME: 2020/8/21-15:29 INSTRUCTIONS: 七牛token """ from qiniu import Auth, put_file from main.settings import QINIU_ACCESS_KEY, QINIU_SECRET_KEY # 构建鉴权对象 q = Auth(QINIU_ACCESS_KEY, QINIU_SECRET_KEY)
def test_noKey(self): with pytest.raises(ValueError): Auth(None, None).token('nokey') with pytest.raises(ValueError): Auth('', '').token('nokey')
def auth_request(self): if not self.auth: self.auth = Auth(self.access_key[0], self.secret_key[0]) return self.auth
def __init__(self, bucket_name): access_key = '2Cr1NjNXhoWJpZ3NRtAbJw2yPhP7f0Qa_q0DfJcq' secret_key = 'bJWSEUKLU1xBmMZPEnT9qUKeBp_ZutBkkH5UEW9g' self.q = Auth(access_key, secret_key) # 要上传的空间 self.bucket_name = bucket_name
def qiniu_download(address, file_path): access_key = 'ZSC-X2p4HG5uvEtfmn5fsTZ5nqB3h54oKjHt0tU6' secret_key = 'Ya8qYwIDXZn6jSJDMz_ottWWOZqlbV8bDTNfCGO0' q = Auth(access_key, secret_key) if address.startswith('qiniu:'): address = address.replace('qiniu:', '') private_url = q.private_download_url(address, expires=3600) if os.path.isdir(file_path): file_path = os.path.join(file_path, str(uuid.uuid4())) try: fpath, _ = urllib.request.urlretrieve(private_url, file_path) statinfo = os.stat(fpath) size = statinfo.st_size if size == 0: logger.error('couldnt download data') return None return file_path except: logger.error('couldnt download data') return None # import tarfile # import subprocess # # def _recursive_tar(root_path, path, tar, ignore=None): # if path.split('/')[-1][0] == '.': # return # # if os.path.isdir(path): # for sub_path in os.listdir(path): # _recursive_tar(root_path, os.path.join(path, sub_path), tar) # else: # if ignore is not None: # if path.split('/')[-1] == ignore: # return # arcname = os.path.relpath(path, root_path) # tar.add(path, arcname=arcname) # # random_code_package_name = str(uuid.uuid4()) # code_tar_path = os.path.join('/Users/Jian/Downloads/aaa', '%s_code.tar.gz' % random_code_package_name) # tar = tarfile.open(code_tar_path, 'w:gz') # for sub_path in os.listdir('/Users/Jian/Downloads/aaa'): # _recursive_tar('/Users/Jian/Downloads/aaa', # os.path.join('/Users/Jian/Downloads/aaa', sub_path), # tar, # ignore='%s_code.tar.gz' % random_code_package_name) # tar.close() # # crypto_code = str(uuid.uuid4()) # # crypto_shell = 'openssl enc -e -aes256 -in %s -out %s -k %s' % ( # '%s_code.tar.gz' % random_code_package_name, # '%s_code_ssl.tar.gz' % random_code_package_name, # crypto_code) # subprocess.call(crypto_shell, shell=True, cwd='/Users/Jian/Downloads/aaa') # # # 解密 # decrypto_shell = 'openssl enc -d -aes256 -in %s -out %s -k %s'%('%s_code_ssl.tar.gz' % random_code_package_name, # '%s_code.tar.gz' % random_code_package_name, # crypto_code) # subprocess.call(decrypto_shell, shell=True, cwd='/Users/Jian/Downloads/aaa') # # qiniu_address = qiniu_upload(code_tar_path, bucket='mltalker', max_size=10) # # print(qiniu_address) # # qiniu_download('http://pbzz7zw0y.bkt.clouddn.com/14697433-5bd9-4b3c-a392-ba72172c666e_code.tar.gz', '/Users/Jian/Downloads/zj')
try: if file_obj.multiple_chunks(): for chunk in file_obj.chunks(): f.write(chunk) else: f.write(file_obj.read()) except Exception, e: log.error(repr(e)) ret['error'] = e finally: f.close() ret['status'] = True try: tmpfile_path = os.path.join('.', file_obj.name) if os.path.exists(tmpfile_path): q = Auth(self.access_key, self.secret_key) log.info("begin base64 filename") file_name_base64 = base64.b64encode(self.to_str(file_obj.name)) log.info( "filename=%s, filenametype=%s, base64filename=%s" % (file_obj.name, type(file_obj.name), file_name_base64)) key = "%s-%s" % (uuid.uuid1(), file_name_base64) token = q.upload_token(self.bucket_name, key, 3600) ret, info = put_file(token, key, tmpfile_path) if info.status_code == 200: ret['url'] = "%s/%s" % (self.base_url, key) else: ret['url'] = "" os.remove(tmpfile_path) except Exception, e: log.error(repr(e))
# -*- coding: utf-8 -*- import logging from qiniu import Auth, BucketManager, build_batch_delete from base import app _LOGGER = logging.getLogger(__name__) EXPIRE_TIME = 3600 # 1 hour Q = Auth(app.config.get('QINIU_ACCESS_KEY'), app.config.get('QINIU_SECERET_KEY')) def generate_token(): token = Q.upload_token(app.config.get('QINIU_BUCKET'), expires=EXPIRE_TIME) return token def delete_data_by_url(urls, bucket=app.config.get('QINIU_BUCKET'), key_prefix=''): keys = [] for url in urls: if not url.endswith('/'): url += '/' key = url.split('/')[-2] if key_prefix: key = '%s/%s' % (key_prefix, key) keys.append(key)
from dateutil.relativedelta import relativedelta from flask import request from icalendar import Calendar, Event from pytz import timezone from qiniu import Auth, put_file from global_config import qiniu from utils.decorators.check_sign import check_sign from utils.decorators.request_limit import request_limit from . import api cst_tz = timezone('Asia/Shanghai') utc_tz = timezone('UTC') q = Auth(qiniu['access_key'], qiniu['secret_key']) bucket_name = 'blog_cdn' with open('static/firstWeekDateTime') as file: first_week = file.read() @api.route('/timetable/export', methods=['POST']) @check_sign(set()) @request_limit() def handle_to_ical(): arguments: dict = request.get_json() timetable = arguments["timetable"] first_monday = arguments.get("firstWeekDateTime", first_week) rule = re.compile(r"[^a-zA-Z0-9\-,]") cal = Calendar() cal['version'] = '2.0'
#!/usr/bin/env python # encoding: utf-8 """ @author: william @contact: [email protected] @site: http://www.xiaolewei.com @file: uploader.py @time: 03/03/2018 12:15 """ import time from qiniu import Auth, put_file, BucketManager from core import config, logger import random _q = Auth(config.get('app.qiniu.access_key'), config.get('app.qiniu.secret_key')) _bucket = config.get('app.qiniu.bucket') _domain = config.get('app.qiniu.domain') _bucket_manager = BucketManager(_q) def upload(url: str): key = 'yugong/' + str(int(time.time())) + str(random.random()) + '.jpg' token = _q.upload_token(_bucket, key, 3600) try_time = 3 while try_time >= 0: # fetch resource on network if url.startswith('http'): ret, info = _bucket_manager.fetch(url, _bucket, key) else: ret, info = put_file(token, key, url)
def get_private_url(username, path, filename): q = Auth(settings.QINIU_ACCESS_KEY, settings.QINIU_SECRET_KEY) # 授权 base_url = ''.join([settings.QINIU_DOMAIN, username, path, '/', filename]) return q.private_download_url(base_url, expires=3600)
def generate_upload_token(): q = Auth(ACCESS_KEY, SECRET_KEY) token = q.upload_token('blog') return token
# -*- coding: utf-8 -*- from Ch import app from qiniu import Auth, put_stream, put_data import os #需要填写你的 Access Key 和 Secret Key access_key = app.config['QINIU_ACCESS_KEY'] secret_key = app.config['QINIU_SECRET_KEY'] #构建鉴权对象 q = Auth(access_key, secret_key) #要上传的空间 bucket_name = app.config['QINIU_BUCKET_NAME'] domain_prefix = app.config['QINIU_DOMAIN'] def qiniu_upload_file(source_file, save_file_name): # 生成上传 Token,可以指定过期时间等 token = q.upload_token(bucket_name, save_file_name) ret, info = put_data(token, save_file_name, source_file.stream) print type(info.status_code), info if info.status_code == 200: return domain_prefix + save_file_name return None
import string import tinify import urllib import sqlite3 import operator from hashlib import md5 from qiniu import Auth, put_file, etag ak = '' sk = '' domain = 'xxxxxx.bkt.clouddn.com' # 上传域名 bucket = 'xxxxxx-pic-bed' # 空间名称 tinify.key = '' # 设置tinipng的key q = Auth(ak, sk) # 七牛认证 md_loc = '' # md地址 need_zip = True def upload_file(upload_file_name): ''' 根据给定的图片名上传图片,并返回图片地址和一些上传信息 ''' rstr = str(time.time()) + ''.join( random.sample('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', 12)) key = md5(rstr.encode('utf-8')).hexdigest() # 上传到七牛后的图片名 mime_type = 'image/%s' % upload_file_name[upload_file_name.rfind('.') + 1:] token = q.upload_token(bucket, key) ret, info = put_file(token,