-
Notifications
You must be signed in to change notification settings - Fork 137
File uploads - locally and on s3 #66
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
36 commits
Select commit
Hold shift + click to select a range
f76e4fc
Draft uploading files locally and on s3
kbadova c4149f9
Drop duplication of "/files" in files urls
kbadova 421cb5d
Add file.uploaded_at field
kbadova 7fe1d22
Add an api for verifying a file upload
kbadova a13a9b3
Add media folder to .gitignore
kbadova 29b870e
Setup media root and media dir. Make sure django sees aws settings
kbadova 4d39c2e
Import timezone from django.utils
kbadova 7068073
Send session key as auth headers when uploading files locally
kbadova 3a54369
MAke file field optional
kbadova d3a2349
Accept integers in url params instead of uuids
kbadova 31b9ea2
Fix generating an upload url
kbadova c42ef6e
Make sure uploaded files can be served by the BE
kbadova a15ac6c
Iteration 1: Local file upload via Django admin
RadoRado 94e72c9
Iteration 2: S3 file upload via Django admin
RadoRado 356537e
Iteration 3: API for direct upload
RadoRado d315a7b
Iteration 4: API for pass-thru upload + s3
RadoRado 0b2b392
Update comment on why are we doing this
RadoRado f558837
Iteration 5: API + Pass-thru + local upload
RadoRado 11e525f
fixup! Iteration 5: API + Pass-thru + local upload
RadoRado e8a9bff
fixup! fixup! Iteration 5: API + Pass-thru + local upload
RadoRado 05f0bc8
Introduce `FileDirectUploadService` to serve as an example
RadoRado d328ad0
Partially fix `mypy`
RadoRado 50cd1a0
Move stubs to local file
RadoRado a337a92
Add `mypy.ini`
RadoRado e0383bd
Explicitly specify mypy config
RadoRado e652bb7
Check mypy version
RadoRado 315db5f
Introduce `S3Credentials`
RadoRado 079561e
Introduce `FilePassThruUploadService`
RadoRado f00ebbe
Introduce enums for settings
RadoRado c5bcd1e
fixup! Introduce enums for settings
RadoRado f5427b9
Move `BASE_DIR` to `config.env`
RadoRado cf7817d
Rename `SERVER_HOST_DOMAIN` to `APP_DOMAIN`
RadoRado 52cc46b
Properly calculate `BASE_DIR`
RadoRado 1bf7f2f
Fix enum/string checks
RadoRado a9fa38d
Add more settings to `.env.example`
RadoRado bc83158
Add the shape of the presigned data
RadoRado File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,2 +1,10 @@ | ||
PYTHONBREAKPOINT=ipdb.set_trace | ||
SENTRY_DSN="" | ||
|
||
FILE_UPLOAD_STRATEGY="direct" # pass-thru | ||
FILE_UPLOAD_STORAGE="local" # s3 | ||
|
||
AWS_S3_ACCESS_KEY_ID="" | ||
AWS_S3_SECRET_ACCESS_KEY="" | ||
AWS_STORAGE_BUCKET_NAME="django-styleguide-example" | ||
AWS_S3_REGION_NAME="eu-central-1" |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -127,3 +127,7 @@ dmypy.json | |
|
||
# Pyre type checker | ||
.pyre/ | ||
|
||
|
||
# media files | ||
/media |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,3 +1,15 @@ | ||
from django.core.exceptions import ImproperlyConfigured | ||
|
||
import environ | ||
|
||
env = environ.Env() | ||
|
||
BASE_DIR = environ.Path(__file__) - 2 | ||
|
||
|
||
def env_to_enum(enum_cls, value): | ||
for x in enum_cls: | ||
if x.value == value: | ||
return x | ||
|
||
raise ImproperlyConfigured(f"Env value {repr(value)} could not be found in {repr(enum_cls)}") |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,36 @@ | ||
import os | ||
|
||
from config.env import BASE_DIR, env, env_to_enum | ||
|
||
from styleguide_example.files.enums import FileUploadStrategy, FileUploadStorage | ||
|
||
|
||
FILE_UPLOAD_STRATEGY = env_to_enum( | ||
FileUploadStrategy, | ||
env("FILE_UPLOAD_STRATEGY", default="direct") | ||
) | ||
FILE_UPLOAD_STORAGE = env_to_enum( | ||
FileUploadStorage, | ||
env("FILE_UPLOAD_STORAGE", default="local") | ||
) | ||
|
||
if FILE_UPLOAD_STORAGE == FileUploadStorage.LOCAL: | ||
MEDIA_ROOT_NAME = "media" | ||
MEDIA_ROOT = os.path.join(BASE_DIR, MEDIA_ROOT_NAME) | ||
MEDIA_URL = f"/{MEDIA_ROOT_NAME}/" | ||
|
||
if FILE_UPLOAD_STORAGE == FileUploadStorage.S3: | ||
# Using django-storages | ||
# https://django-storages.readthedocs.io/en/latest/backends/amazon-S3.html | ||
DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' | ||
|
||
AWS_S3_ACCESS_KEY_ID = env("AWS_S3_ACCESS_KEY_ID") | ||
AWS_S3_SECRET_ACCESS_KEY = env("AWS_S3_SECRET_ACCESS_KEY") | ||
AWS_STORAGE_BUCKET_NAME = env("AWS_STORAGE_BUCKET_NAME") | ||
AWS_S3_REGION_NAME = env("AWS_S3_REGION_NAME") | ||
AWS_S3_SIGNATURE_VERSION = env("AWS_S3_SIGNATURE_VERSION", default="s3v4") | ||
|
||
# https://docs.aws.amazon.com/AmazonS3/latest/userguide/acl-overview.html#canned-acl | ||
AWS_DEFAULT_ACL = env("AWS_DEFAULT_ACL", default="private") | ||
|
||
AWS_PRESIGNED_EXPIRY = env.int("AWS_PRESIGNED_EXPIRY", default=10) # seconds |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,35 @@ | ||
[mypy] | ||
plugins = | ||
mypy_django_plugin.main, | ||
mypy_drf_plugin.main | ||
|
||
[mypy.plugins.django-stubs] | ||
django_settings_module = "config.django.base" | ||
|
||
[mypy-config.*] | ||
# Ignore everything related to Django config | ||
ignore_errors = true | ||
|
||
[mypy-styleguide_example.*.migrations.*] | ||
# Ignore Django migrations | ||
ignore_errors = true | ||
|
||
[mypy-celery.*] | ||
# Remove this when celery stubs are present | ||
ignore_missing_imports = True | ||
|
||
[mypy-django_celery_beat.*] | ||
# Remove this when django_celery_beat stubs are present | ||
ignore_missing_imports = True | ||
|
||
[mypy-django_filters.*] | ||
# Remove this when django_filters stubs are present | ||
ignore_missing_imports = True | ||
|
||
[mypy-factory.*] | ||
# Remove this when factory stubs are present | ||
ignore_missing_imports = True | ||
|
||
[mypy-rest_framework_jwt.*] | ||
# Remove this when rest_framework_jwt stubs are present | ||
ignore_missing_imports = True |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -14,3 +14,4 @@ ipython==8.2.0 | |
mypy==0.942 | ||
django-stubs==1.9.0 | ||
djangorestframework-stubs==1.4.0 | ||
boto3-stubs==1.21.32 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Empty file.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,77 @@ | ||
from django import forms | ||
|
||
from django.contrib import admin, messages | ||
from django.core.exceptions import ValidationError | ||
|
||
from styleguide_example.files.models import File | ||
from styleguide_example.files.services import ( | ||
FileDirectUploadService | ||
) | ||
|
||
|
||
class FileForm(forms.ModelForm): | ||
class Meta: | ||
model = File | ||
fields = ["file", "uploaded_by"] | ||
|
||
|
||
@admin.register(File) | ||
class FileAdmin(admin.ModelAdmin): | ||
list_display = [ | ||
"id", | ||
"original_file_name", | ||
"file_name", | ||
"file_type", | ||
"url", | ||
"uploaded_by", | ||
"created_at", | ||
"upload_finished_at", | ||
"is_valid", | ||
] | ||
list_select_related = ["uploaded_by"] | ||
|
||
ordering = ["-created_at"] | ||
|
||
def get_form(self, request, obj=None, **kwargs): | ||
""" | ||
That's a bit of a hack | ||
Dynamically change self.form, before delegating to the actual ModelAdmin.get_form | ||
Proper kwargs are form, fields, exclude, formfield_callback | ||
""" | ||
if obj is None: | ||
self.form = FileForm | ||
|
||
return super().get_form(request, obj, **kwargs) | ||
|
||
def get_readonly_fields(self, request, obj=None): | ||
""" | ||
We want to show those fields only when we have an existing object. | ||
""" | ||
|
||
if obj is not None: | ||
return [ | ||
"original_file_name", | ||
"file_name", | ||
"file_type", | ||
"created_at", | ||
"updated_at", | ||
"upload_finished_at" | ||
] | ||
|
||
return [] | ||
|
||
def save_model(self, request, obj, form, change): | ||
try: | ||
cleaned_data = form.cleaned_data | ||
|
||
service = FileDirectUploadService( | ||
file_obj=cleaned_data["file"], | ||
user=cleaned_data["uploaded_by"] | ||
) | ||
|
||
if change: | ||
service.update(file=obj) | ||
else: | ||
service.create() | ||
except ValidationError as exc: | ||
self.message_user(request, str(exc), messages.ERROR) |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.