人工智能 大数据 计算机科学

django项目使用boto3进行文件存储+S3 Browser

2019-03-20  本文已影响0人  LittleJessy

项目中的图片需要上传到Amazon S3云存储服务上,所以项目中添加相关配置及代码(当前bucket已经存在)

settings.py文件中设置

image.png

编写公共模块AwsS3.py

# _*_ coding:utf-8 _*_
from public.log import *
from django.conf import settings
from boto3.session import Session
import django
from botocore.client import Config


os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'QAPlatform.settings')
django.setup()


class AwsS3(object):
    def __init__(self):
        self.BUCKET_NAME = settings.BUCKET_NAME
        self.aws_access_key_id = settings.AWS_ACCESS_KEY_ID
        self.aws_secret_access_key = settings.AWS_SECRET_ACCESS_KEY
        self.endpoint_url = settings.ENDPOINT_URL
        self.region_name = settings.REGIN_NAME
        self.session = Session(aws_access_key_id=self.aws_access_key_id,
                               aws_secret_access_key=self.aws_secret_access_key, region_name=self.region_name)
        self.s3 = self.session.resource('s3', endpoint_url=self.endpoint_url, verify=False,
                                        config=Config(signature_version='s3v4'))
        self.client = self.session.client('s3')

    # 将本地文件传到s3的指定bucket中
    def uploadFile(self, file_path, upload_path):
        if os.path.exists(file_path):
            upload_data = open(file_path, 'rb')
            upload_key = upload_path
            try:
                self.s3.Bucket(self.BUCKET_NAME).put_object(Key=upload_key, Body=upload_data)
                # 设置上传对象可读权限
                object_acl = self.s3.ObjectAcl(self.BUCKET_NAME,upload_key)
                object_acl.put(ACL='public-read')

                writeLog_info("bucket_name=%s,file_path=%s,key=%s" % (self.BUCKET_NAME, file_path, upload_path))
                return True
            except Exception as e:
                writeLog_error('%s,上传失败:%s' % (file_path, e))
                return False
        else:
            writeLog_error("file_path=%s, not exists" % file_path)
            return False

    # 下载文件
    def downloadFile(self, download_path, key):
        try:
            self.s3.Object(self.BUCKET_NAME, key).download_file(download_path)
            writeLog_info("bucket_name=%s,path=%s,key=%s,下载成功!" % (self.BUCKET_NAME, download_path, key))
            return True
        except Exception as e:
            writeLog_error("%s下载失败: %s" % (key, e))
            return False

    # 删除s3上的文件
    def deleteFile(self, key):
        self.client.delete_object(Bucket=self.BUCKET_NAME, Key=key)
        writeLog_info("bucket_name=%s,key=%s" % (self.BUCKET_NAME, key))

vews.py中调用即可实现文件上传

S3 Browser

S3 Browser 为S3的图形化界面工具:
[下载网址](http://s3browser.com/

[keygen破解版](http://appdol.com/2017/01/25/s3-browser-pro-6-5-9-crack-serial-key-keygen-download/
配置:

image.png image.png

上传文件后


image.png
上一篇下一篇

猜你喜欢

热点阅读