小编这次要给大家分享的是python如何实现上传文件到OSS,文章内容丰富,感兴趣的小伙伴可以来了解一下,希望大家阅读完这篇文章之后能够有所收获。

基础环境

# +++++ 阿里云OSS开发指南里都有详细的步骤,在这里整理了一下自己需要的东西# 确定开发环境,centOS默认安装了python2.7# python -V# 安装python开发包# yum install -y python-devel# 安装OSS的sdk# yum install -y python-pip# pip2.7 install oss2# 验证oss2是否安装正确'''>>> import oss2>>> oss2.__version__'2.6.0''''# 验证OSS扩展库crcmod是否安装'''在python环境中,输入一下内容,如果有错误信息,则说明扩展库安装不成功,默认安装oss2的时候会安装扩展库>>> import crcmod._crcfunext如果出现安装不成功,则按一下步骤安装:1、执行以下命令卸载crcmod# pip uninstall crcmod2、安装python-devel3、执行以下命令重新安装crcmod# pip install crcmod'''

小文件上传

#!/usr/bin/env python# -*- coding: utf-8 -*-import oss2# 阿里云主账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维,请登录 https://ram.console.aliyun.com 创建RAM账号。auth = oss2.Auth('<yourAccessKeyId>', '<yourAccessKeySecret>')# Endpoint以杭州为例,其它Region请按实际情况填写。bucket = oss2.Bucket(auth, 'http://oss-cn-hangzhou.aliyuncs.com', '<yourBucketName>')# 必须以二进制的方式打开文件,因为需要知道文件包含的字节数。with open('<yourLocalFile>', 'rb') as fileobj: # Seek方法用于指定从第1000个字节位置开始读写。上传时会从您指定的第1000个字节位置开始上传,直到文件结束。 fileobj.seek(1000, os.SEEK_SET) # Tell方法用于返回当前位置。 current = fileobj.tell() bucket.put_object('<yourObjectName>', fileobj)


分片上传

# -*- coding: utf-8 -*-import osfrom oss2 import SizedFileAdapter, determine_part_sizefrom oss2.models import PartInfoimport oss2# 阿里云主账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维,请登录 https://ram.console.aliyun.com 创建RAM账号。auth = oss2.Auth('<yourAccessKeyId>', '<yourAccessKeySecret>')# Endpoint以杭州为例,其它Region请按实际情况填写。bucket = oss2.Bucket(auth, 'http://oss-cn-hangzhou.aliyuncs.com', '<yourBucketName>')key = '<yourObjectName>'filename = '<yourLocalFile>'total_size = os.path.getsize(filename)# determine_part_size方法用来确定分片大小。part_size = determine_part_size(total_size, preferred_size=100 * 1024)# 初始化分片。upload_id = bucket.init_multipart_upload(key).upload_idparts = []# 逐个上传分片。with open(filename, 'rb') as fileobj: part_number = 1 offset = 0 while offset < total_size: num_to_upload = min(part_size, total_size - offset) # SizedFileAdapter(fileobj, size)方法会生成一个新的文件对象,重新计算起始追加位置。 result = bucket.upload_part(key, upload_id, part_number, SizedFileAdapter(fileobj, num_to_upload)) parts.append(PartInfo(part_number, result.etag)) offset += num_to_upload part_number += 1# 完成分片上传。bucket.complete_multipart_upload(key, upload_id, parts)# 验证分片上传。with open(filename, 'rb') as fileobj: assert bucket.get_object(key).read() == fileobj.read()

看完这篇关于python如何实现上传文件到OSS的文章,如果觉得文章内容写得不错的话,可以把它分享出去给更多人看到。