参考官方接口文档
https://developer.qiniu.com/kodo/sdk/1242/python
1、安装
pip install qiniu
2、准备工作
注册账号登陆,个人中心获取Access Key 和 Secret Key
创建对象存储空间
进入空间获取测试域名
3、使用python进行上传
from qiniu import Auth, put_file
# 获取Access Key 和 Secret Key 后,进行初始化对接:
q = Auth(access_key='OHVEpYqmlZXdJ2oqoL6gVCvf4m37s5M-rHqDGid5',
secret_key='Q2yXeCcdqqc3z5k5TysLUZrn7sYXTBavch6kGL9q')
# 上传的七牛云空间
bucket_name = 'md-feifei'
# 上传后保存的文件名
key = '1.jpg'
# 生成上传token
token = q.upload_token(bucket_name, key)
# 要上传文件的路径
localfile = './126_30003.jpg'
ret, info = put_file(token, key, localfile)
# 拼接路径 qj5s0uqce.hb-bkt.clouddn.com这个是创建空间分配的测试域名
image_file = 'http://qj5s0uqce.hb-bkt.clouddn.com/' + ret.get('key')
print(image_file) # http://qj5s0uqce.hb-bkt.clouddn.com/1.jpg
4、函数封装
from qiniu import Auth, put_file, etag
from mdpro.settings import BASE_DIR
import uuid
def qiniu_token(bucked_name):
q = Auth(access_key='hmv--oUg0_UbsrqPX4_E-OlWsVRfYkpmmSa1b_bv',
secret_key='9tW8bwz3VQonIUbuuAWa_Atpp8rayHZTv_oZGIrh')
token = q.upload_token(bucked_name)
return token
def upload_img(bucked_name, file_path, domain_name):
"""
收集本地信息到云服务器上
参考地址:https://developer.qiniu.com/kodo/sdk/1242/python
"""
# 指定上传空间,获取token
token = qiniu_token(bucked_name)
# 指定图片名称
file_name = '{}.png'.format(uuid.uuid4())
ret, info = put_file(token, file_name, file_path)
img_url = domain_name + ret.get('key')
return img_url
if __name__ == '__main__':
bucked_name = 'h2002a'
file_path = '{}\\myutils\\123.png'.format(BASE_DIR)
domain_name = 'http://qj5ps2dbi.hb-bkt.clouddn.com/'
print(upload_img(bucked_name, file_path, domain_name))