Flask使用阿里云OSS对象存储保存附件

当附件文件数据太大太多的时候我们需要开始考虑使用云存储,云存储的出现,极大的解决了原有硬件资源无法满足存储场景的需求,即使你的规模达到P级,也无需担心存储的瓶颈和读取的缓慢,这里我们就使用flask框架使用阿里云的OSS将文件保存到云端,下面是操作方法

1)首先我们安装阿里云的OSS模块

pip install oss2

2)去官网开通阿里云对象存储并创建buket

TIM截图20181122102054.jpg

TIM截图20181122102202.jpg

这里有几个地方需要注意,一个是创建BUKET的时候属性是公共读,如果你是要提供存储公开给大家读取的话就是这样

使用API的时候注意EndPoint填写外网的,如果你是使用阿里云的ECS,经典网络和专有网络就用下面两个,按你的ECS情况来选择使用哪一个

这里演示代码,直接用我的信息吧,我用的不是阿里云服务器,以下yourAccessKeyId和yourAccessKeySecret换成你自己的,然后我的EndPoint是oss-cn-beijing.aliyuncs.com,buket名字是merci-buket

3)实例代码,直接上我的代码

from werkzeug.utils import secure_filename
import oss2

auth = oss2.Auth('<Your AccessKey>', '<your AccessKeySecret>')
bucket = oss2.Bucket(auth, 'oss-cn-beijing.aliyuncs.com', 'merci-buket')
#上传
@tools.route('/upload', methods=['POST', 'GET'])
def upload():
    if request.method == "POST":
        f = request.files['file']
        attchment_dir = time.strftime("%Y/%m%d/", time.localtime())
        upload_path = os.path.join("attchment/uploadfile/", attchment_dir)
        isExist = os.path.exists(upload_path)
        if not isExist:
            os.makedirs(upload_path, 0o777)
        src = os.path.join(upload_path + secure_filename(f.filename))
        f.save(src)
        #将文件上传到oss
        bucket.put_object_from_file(src,src)
        datas = {
            "code":0,
            "msg":"",
            "data":{
                "src":src
            }
        }
        return jsonify(datas)
        
#删除
@tools.route('/deleteobject', methods=['POST', 'GET'])
def deleteObject():
    objectname = request.args.get('name')
    bucket.delete_object(objectname)
    return '删除成功!'


内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://sulao.cn/post/582.html

我要评论

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。