Skip to content

Commit

Permalink
Set the content type and disposition of webp files uploaded to S3
Browse files Browse the repository at this point in the history
  • Loading branch information
TkTech authored Dec 14, 2022
1 parent 3404b15 commit 0d8b7db
Show file tree
Hide file tree
Showing 4 changed files with 16 additions and 2 deletions.
1 change: 1 addition & 0 deletions activities/views/compose.py
Original file line number Diff line number Diff line change
Expand Up @@ -216,6 +216,7 @@ def form_valid(self, form):
name=form.cleaned_data.get("description"),
state=PostAttachmentStates.fetched,
)

attachment.file.save(
main_file.name,
main_file,
Expand Down
12 changes: 12 additions & 0 deletions core/uploads.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import secrets

from django.utils import timezone
from storages.backends.s3boto3 import S3Boto3Storage


def upload_namer(prefix, instance, filename):
Expand All @@ -12,3 +13,14 @@ def upload_namer(prefix, instance, filename):
_, old_extension = os.path.splitext(filename)
new_filename = secrets.token_urlsafe(20)
return f"{prefix}/{now.year}/{now.month}/{now.day}/{new_filename}{old_extension}"


class TakaheS3Storage(S3Boto3Storage):
def get_object_parameters(self, name: str):
params = self.object_parameters.copy()

if name.endswith(".webp"):
params["ContentDisposition"] = "inline"
params["ContentType"] = "image/webp"

return params
2 changes: 1 addition & 1 deletion runtime.txt
Original file line number Diff line number Diff line change
@@ -1 +1 @@
python-3.11.0
python-3.11.1
3 changes: 2 additions & 1 deletion takahe/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -346,7 +346,8 @@ class Config:
GS_BUCKET_NAME = parsed.hostname
GS_QUERYSTRING_AUTH = False
elif parsed.scheme == "s3":
DEFAULT_FILE_STORAGE = "storages.backends.s3boto3.S3Boto3Storage"
# DEFAULT_FILE_STORAGE = "storages.backends.s3boto3.S3Boto3Storage"
DEFAULT_FILE_STORAGE = "core.uploads.TakaheS3Storage"
AWS_STORAGE_BUCKET_NAME = parsed.path.lstrip("/")
AWS_QUERYSTRING_AUTH = False
AWS_DEFAULT_ACL = "public-read"
Expand Down

0 comments on commit 0d8b7db

Please sign in to comment.