上一篇我们已经说过又拍云的常用操作,今天我们讲一下结合多线程实现异步上传

当我们使用第三方依赖,要注意模块是不是最新依赖,进行更新

UPYUN Python SDK文档:点击跳转
查看最新python SDK:点击跳转

多线程异步实现又拍云上传

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import upyun  # 又拍云
import os # 文件模块
import threading # 多线程模块

# 新建又拍云实例
# 三个参数,又拍云服务名称,操作员名称,操作员密码
up = upyun.UpYun('服务名称', '操作员名称', '操作员密码')
# 分块上传
uploader = up.init_multi_uploader('/upyun_python/upyun_sanguo.mp4')
#同步上传
# uploader.upload(0,os.urandom(1024*1024))
# uploader.upload(1,os.urandom(1024*1024))

#采用多线程调用上传
#创建线程池
threads = []
#uploader.upload不加括号,这里是声明,不是调用,调用的话还是同步
#参数写在args里,(0声明异步上传序号)
t1 = threading.Thread(target=uploader.upload,args=(0,os.urandom(1024*1024)))
# #添加到线程池
threads.append(t1)
t2 = threading.Thread(target=uploader.upload,args=(1,os.urandom(1024*1024)))
threads.append(t2)

#启动多线程
for t in threads:
t.start()
# #阻塞主线程
t.join()
#
# # #声明调用结束
res = uploader.complete()

多线程异步对文件进行分块上传

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#上传又拍云文件
class Upyun_Post(APIView):
def post(self,request):
# 获取视频文件
file = request.FILES.get('file')
print(file)
up = upyun.UpYun('服务名称', '操作员名称', '操作员密码')
uploader = up.init_multi_uploader("/upyun-python-sdk/%s" % file, part_size=(1024 * 2048))
threads = []
for index, value in enumerate(file.chunks(chunk_size=(1024 * 2048))):
t = threading.Thread(target=uploader.upload, args=(index, value))
threads.append(t)
for i in threads:
i.start()
i.join()
res = uploader.complete()
return Response({'code':200,'message':'上传成功'})
# return HttpResponse(json.dumps({'filename': file}), content_type='application/json')

评论





载入天数...载入时分秒...

Blog content follows the Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0) License

Use WZH as theme, total visits times