本文整理汇总了Python中qiniu.Auth类的典型用法代码示例。如果您正苦于以下问题:Python Auth类的具体用法?Python Auth怎么用?Python Auth使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Auth类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: upload_qiniu_by_path
def upload_qiniu_by_path(access_key, secret_key, bucket_name, key_prefix,
pool_number, path, delete=False):
q = Auth(access_key, secret_key)
mime_type = "text/plain"
params = {'x:a': 'a'}
pool = Pool(pool_number)
for dirpath, dirnames, filenames in os.walk(path):
print(dirpath)
if len(filenames) > 0:
for filename in filenames:
if filename.startswith('.'):
continue
localfile = os.path.join(dirpath, filename)
key = os.path.join(key_prefix, localfile.replace(path, '')[1:])
token = q.upload_token(bucket_name, key)
pool.spawn(
down,
token=token,
key=key,
localfile=localfile,
mime_type=mime_type,
delete=delete
)
示例2: QiNiuProvider
class QiNiuProvider(object):
def __init__(self, access_key, secret_key, bucket_name, imageServerUrl):
self.access_key = access_key
self.secret_key = secret_key
self.bucket_name = bucket_name
self.imageServerUrl = imageServerUrl
self.credentials = Auth(self.access_key, self.secret_key)
def token(self):
return self.credentials.upload_token(self.bucket_name)
def store(self, raw):
key = hash(str(uuid.uuid1()))
upload_token = self.credentials.upload_token(self.bucket_name, key)
ret, err = put_data(upload_token, key, raw)
if ret is not None:
return "%s/%s" % (self.imageServerUrl, ret['key'])
else:
logging.error('upload error.')
def store_file(self, file_path, file_name):
upload_token = self.credentials.upload_token(self.bucket_name, file_name)
ret, err = put_file(upload_token, file_name, file_path)
if ret is not None:
return "%s/%s" % (self.imageServerUrl, ret['key'])
else:
logging.error('upload: %s error.' % file_name)
示例3: Qiniu
class Qiniu(object):
def init_app(self, app):
access_key = app.config.get('QINIU_ACCESS_KEY')
secret_key = app.config.get('QINIU_SECRET_KEY')
self.app = app
self.bucket = app.config.get('QINIU_BUCKET')
self.auth = Auth(access_key, secret_key)
def upload_file(self, filename, filepath):
"""上传本地文件"""
token = self.auth.upload_token(self.bucket, filename)
ret, info = put_file(token, filename, filepath)
if info.exception is not None:
raise UploadError(info)
def upload_data(self, filename, data):
"""上传二进制数据"""
token = self.auth.upload_token(self.bucket, filename)
ret, info = put_data(token, filename, data)
if info.exception is not None:
raise UploadError(info)
def generate_token(self, filename=None, policy=None):
"""生成上传凭证"""
return self.auth.upload_token(self.bucket, filename, policy=policy)
示例4: get
def get(self):
access_key = 'YOUR_ACCESS_KEY'
secret_key = 'YOUR_SECRET_KEY'
q = Auth(access_key, secret_key)
bucket_name = 'YOUR_BUCKET_NAME'
# to set the uploaded file rename to YYYYMMDD_HHMMSS_filename
# if the filename was "test.jpg", then the new filename will be "20160101_083054_test.jpg"
# SEE MORE: http://developer.qiniu.com/article/kodo/kodo-developer/up/vars.html#magicvar
policy = {"saveKey": "$(year)$(mon)$(day)_$(hour)$(min)$(sec)_$(fname)"}
# in the source of qiniu/auth.py, the function upload_token takes 5 arguments:
# bucket:your bucket_name
# key: the filename you want to set, None means set as ths "saveKey" above
# expires: expires time (second)
# policy: the options to upload,see more: http://developer.qiniu.com/article/developer/security/put-policy.html
#
# def upload_token(self, bucket, key=None, expires=3600, policy=None, strict_policy=True):
token = q.upload_token(bucket_name, None, 3600, policy)
# return as json
self.write(json.dumps({"uptoken":token}))
示例5: generate_upload_token
def generate_upload_token(prefix):
'''
prefix: 'head' or 'content'
return: (token, key)
'''
# modify default upload zone
qiniu.config.set_default(default_zone=qiniu.config.zone1)
# access two keys
access_key = current_app.config['QINIU_ACCESS_KEY']
secret_key = current_app.config['QINIU_SECRET_KEY']
# auth obj
q = Auth(access_key, secret_key)
# upload bucket name
bucket_name = current_app.config['QINIU_BUCKET_NAME']
# achieve file ext name
try:
match = re.finditer(r'.([0-9a-zA-Z]+)$', localfile)
ext = match[-1].group(1)
except:
ext = 'jpg'
# cloud filename
# key = generate_upload_filename(ext, prefix=prefix)
# generate token
token = q.upload_token(bucket_name, None, 3600)
return token
示例6: QiNiu
class QiNiu(object):
def __init__(self):
self.authed = Auth(AccessKey, SecretKey)
def upload(self, data):
"""
:param data:
{
"filename":"",
"filepath":"",
"policy":{}
}
:return:
ret
info
"""
filename = data["filename"]
filepath = data["filepath"]
policy = data.get("policy", {})
if policy:
token = self.authed.upload_token(BucketName, filename, Expired, policy)
else:
token = self.authed.upload_token(BucketName, filename, Expired)
ret, info = put_file(token, filename, filepath)
return ret, info
示例7: loop_qiniu
def loop_qiniu():
while True:
for f in os.listdir(UPLOAD_FOLDER):
if 'tmp' not in f.split('_')[-1]:
os.remove(os.path.join(UPLOAD_FOLDER, f))
# print 'jump out and for one more time'
elif 'tmp0' == f.split('_')[-1]:
continue
elif 'tmp' == f.split('_')[-1]:
print 'start handle %s' % f
f_path = os.path.join(UPLOAD_FOLDER, f)
f_path_new = os.path.join(UPLOAD_FOLDER, f[:-4])
key = f[:-4]
q = Auth(access_key, secret_key)
token = q.upload_token(Bucket, key, 3600)
local_file = f_path
ret, _ = put_file(token, key, local_file)
try:
assert ret['key'] == key
except TypeError:
print 'ret has error'
continue
os.rename(f_path, f_path_new)
print 'end handle %s' % key
print time.strftime("%Y/%y/%d %H:%M:%S", time.localtime(time.time()))
else:
print '<----'
print u'为考虑到的情况'
print time.strftime("%Y/%y/%d %H:%M:%S", time.localtime(time.time()))
print '---->'
print 'pass this time while error', time.strftime("%Y/%y/%d %H:%M:%S", time.localtime(time.time()))
示例8: create
def create(self):
# TODO: 表单验证
image = request.files['image']
# TODO: 解包检查
origin_name, suffix = image.raw_filename.split('.')
data = image.file.read()
data_hash = md5(data).hexdigest()
key = data_hash
model = ImageModel.query.get(data_hash)
if model:
return model.as_dict()
auth = Auth(QINIU_ACCESS_KEY, QINIU_SECRET_KEY)
token = auth.upload_token(
QINIU_BUCKET_NAME, None, 7200,
{
'returnBody': json.dumps({
'key': '$(key)',
'hash': '$(etag)',
'format': '$(imageInfo.format)',
'width': '$(imageInfo.width)',
'height': '$(imageInfo.height)',
}),
'save_key': '$(etag)',
}
)
ret, info = put_data(token, key, data)
model = ImageModel(
hashkey=data_hash, suffix=ret['format'],
width=ret['width'], height=ret['height'])
db.session.add(model)
db.session.commit()
return model.as_dict()
示例9: upload
def upload():
# Get the name of the uploaded file
file = request.files['file']
# Check if the file is one of the allowed types/extensions
if file and allowed_file(file.filename):
# Make the filename safe, remove unsupported chars
filename = secure_filename(file.filename)
# Move the file form the temporal folder to
# the upload folder we setup
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
# Redirect the user to the uploaded_file route, which
# will basicaly show on the browser the uploaded file
path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
access_key = ''
secret_key = ''
bucket_name = ''
q = Auth(access_key, secret_key)
token = q.upload_token(bucket_name, None, 3600)
ret, info = qiniu.put_file(token, filename, path)
return redirect(url_for('uploaded_file', filename=filename))
示例10: uploadsong
def uploadsong(request):
q = Auth('ToNLYIGLfHy5tpKSsRcBV2pw18b20LrYuBdvHaA_', 'rrD25c6RoHoMajmLR8lSz9wW4FcGEHvGMDL4l2zV')
print q
token = q.upload_token('outshineamazing', '')
print token
context = {'uptoken_url':token}
return render(request,'comments/test.html',context)
示例11: uploadToQiNiu
def uploadToQiNiu(filePath,name):
q = Auth(access_key, secret_key)
localfile = filePath
key = name
mime_type = "image/jpeg"
token = q.upload_token(bucket_name, key)
ret, info = put_file(token, key, localfile, mime_type=mime_type, check_crc=True)
示例12: test_upload
def test_upload():
q = Auth(access_key, secret_key)
token = q.upload_token(bucket, mykey.encode('utf-8'))
file = '/tmp/abc.txt'
ret, info = put_file(token, mykey.encode('utf-8'), file, mime_type="text/plain", check_crc=True)
print(info)
print(ret)
示例13: post
def post(self):
for i in request.forms.keys():
print i, request.forms[i], type(request.forms[i])
for i in request.files.keys():
print i, request.files[i], type(request.files[i])
print request.files[i].__dict__
image = request.files['image']
name = image.raw_filename
data = image.file.read()
key = md5('data').hexdigest() + '.' + name.split('.')[-1]
auth = Auth(QINIU_ACCESS_KEY, QINIU_SECRET_KEY)
token = auth.upload_token(
QINIU_BUCKET_NAME, None, 7200,
{
'returnBody': json.dumps({
'key': '$(key)',
'hash': '$(etag)',
'format': '$(imageInfo.format)',
'width': '$(imageInfo.width)',
'height': '$(imageInfo.height)',
}),
'save_key': '$(etag)',
}
)
ret, info = put_data(token, key, data)
示例14: get_token
def get_token(key):
q = Auth(qiniu_access_key, qiniu_secret_key)
# 上传策略仅指定空间名和上传后的文件名,其他参数仅为默认值
token = q.upload_token(qiniu_bucket_name, key)
return token
示例15: storage
def storage(file_data):
try:
#构建鉴权对象
q = Auth(access_key, secret_key)
#要上传的空间
bucket_name = 'ihome'
#上传到七牛后保存的文件名
# key = 'my-python-logo.png';
#生成上传 Token,可以指定过期时间等
token = q.upload_token(bucket_name)
#要上传文件的本地路径
# localfile = './sync/bbb.jpg'
# ret, info = put_file(token, key, localfile)
ret, info = put_data(token, None, file_data)
except Exception as e:
logging.error(e)
raise e
print(ret)
print("*"*16)
print(info)
# assert ret['key'] == key
# assert ret['hash'] == etag(localfile)
print(type(info))
print(info.status_code)
if 200 == info.status_code:
return ret["key"]
else:
raise Exception("上传失败")