[Mobilar] 05 - Multiple Users: using AWS S3 for file uploads
Ref: Python Django Tutorial: Full-Featured Web App Part 13 - Using AWS S3 for File Uploads
Ref: https://django-storages.readthedocs.io/en/latest/
$ pip install django-storages
django-storages is a collection of custom storage backends for Django.
提供了多种云存储方案:
一、创建 S3 Bucket
(1) 视频中版本,未用到。
<?xml version="1.0" encoding="UTF-8"?> <CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"> <CORSRule> <AllowedOrigin>*</AllowedOrigin> <AllowedMethod>GET</AllowedMethod> <AllowedMethod>POST</AllowedMethod> <AllowedMethod>PUT</AllowedMethod> <AllowedHeader>*</AllowedHeader> </CORSRule> </CORSConfiguration>
(2) 这是json 版本,有用到。
[
{
"AllowedHeaders": [
"*"
],
"AllowedMethods": [
"PUT",
"POST",
"DELETE"
],
"AllowedOrigins": [
"*"
],
"ExposeHeaders": []
}
]
二、创建 IAM Role
创建一个具有S3操作的policy和role。
文件 settings.py
EMAIL_HOST_USER = os.environ.get('EMAIL_USER') EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_PASS') AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = os.environ.get('AWS_STORAGE_BUCKET_NAME')
这里就可以注销掉,放弃本地保存的方式。
class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') def __str__(self): return f'{self.user.username} Profile' # def save(self, *args, **kwargs): # super().save(*args, **kwargs) # img = Image.open(self.image.path) # if img.height > 300 or img.width > 300: # output_size = (300, 300) # img.thumbnail(output_size) # img.save(self.image.path)
三、云端 media 文件夹
把本地的文件夹内容如何重定向到S3上呢?
media/ ├── default.jpg └── profile_pics ├── large.jpg ├── large_rbSbk8j.jpg └── pic.jpg
根据 AWS_STORAGE_BUCKET_NAME,就直接将 media的文件夹内容 “原封不动”的重定向到 S3的bucket上了呢,精简的操作。
Notice: 记得再安装 boto3,以及相关的dependencies。
四、多用户 Media 隔离
Ref: Storing Django Static and Media Files on Amazon S3
Ref: Learn Django - Implementing AWS S3 Storage for Static and Media files in Django