Skip to content

Commit

Permalink
Feito upload de arquivos publicos ou privados
Browse files Browse the repository at this point in the history
close #17
  • Loading branch information
renzo authored and renzon committed Aug 22, 2024
1 parent 1050b14 commit ca880f0
Show file tree
Hide file tree
Showing 8 changed files with 161 additions and 1 deletion.
16 changes: 16 additions & 0 deletions backend/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,3 +43,19 @@ acordo com sua necessidade.
Para ler configurações de instância esse projeto usa a lib [python decouple](https://pypi.org/project/python-decouple/).
Ela é importada no arquivo settings.py

## Uploads de arquivos

O projeto está configurado para gravar arquivos publicos ou privados. Por isso, se usar ImageField ou FileField,
O parâmetro "upldat_to" precisar ter prefixo "public" para arquivos que sejam publicos e "private" para privados. Exemplos:

```python
from django.db.models import Model, ImageField, FileField

class UserProfile(Model):
avatar = ImageField(upload_to='public/base/avatars/', null=True, blank=True)

class NotaFiscal(Model):
arquivo = FileField(upload_to='private/base/notas_fiscais/')

```

1 change: 1 addition & 0 deletions backend/devpro/base/admin.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from django.contrib import admin
from django.contrib.admin import ModelAdmin
from django_min_custom_user.admin import MinUserAdmin

from devpro.base.models import User
Expand Down
1 change: 1 addition & 0 deletions backend/devpro/base/models.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from django.db.models import Model
from django_min_custom_user.models import MinAbstractUser


Expand Down
29 changes: 29 additions & 0 deletions backend/devpro/s3_file_handlers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
from storages.backends.s3 import S3Storage


class FileConfigurationError(Exception):
pass


class S3FileStorage(S3Storage):
def url(self, name, parameters=None, expire=None, http_method=None):
url = super().url(name, parameters, expire, http_method)
if name.startswith('public'):
url = url.split('?')[0]
return url

def get_object_parameters(self, name):
parameters = super().get_object_parameters(name)
self._validate(name)
if self._startswith(name, 'public'):
parameters['ACL'] = 'public-read'
else:
parameters['ACL'] = 'private'
return parameters

def _validate(self, name: str):
if not (self._startswith(name, 'public') or self._startswith(name, 'private')):
raise FileConfigurationError(f'property "upload_to" must start with "public" or "private" and it is {name}')

def _startswith(self, name, prefix):
return name.startswith(f'{self.location}/{prefix}')
10 changes: 10 additions & 0 deletions backend/devpro/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -124,17 +124,27 @@
# Configuração para coletar estáticos para o Nginx
STATIC_URL = 'static/'
STATIC_ROOT = BASE_DIR.parent / 'docker/staticfiles/static'
MEDIA_ROOT = BASE_DIR.parent / 'docker/mediafiles'
MEDIA_URL = '/mediafiles/'
else:
STATIC_URL = f'//{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com/static/'

AWS_S3_ACCESS_KEY_ID = config('AWS_S3_ACCESS_KEY_ID')
AWS_S3_SECRET_ACCESS_KEY = config('AWS_S3_SECRET_ACCESS_KEY')
STORAGES = {
"default": {
"BACKEND": "devpro.s3_file_handlers.S3FileStorage",
"OPTIONS": {
'default_acl': 'private',
'location': 'media',
},
},
"staticfiles": {
"BACKEND": "storages.backends.s3.S3Storage",
"OPTIONS": {
'default_acl': 'public-read',
'location': 'static',
'querystring_auth': False
},
},
}
Expand Down
5 changes: 5 additions & 0 deletions backend/devpro/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,14 @@
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
from django.urls import path

urlpatterns = [
path('admin/', admin.site.urls),
]

if settings.AWS_STORAGE_BUCKET_NAME == '':
urlpatterns.extend(static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT))
99 changes: 98 additions & 1 deletion backend/poetry.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions backend/pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ dj-database-url = "^2.2.0"
python-decouple = "^3.8"
django-min-custom-user = "^0.2.0"
django-storages = {extras = ["s3"], version = "^1.14.4"}
pillow = "^10.4.0"


[tool.poetry.group.dev]
Expand Down

0 comments on commit ca880f0

Please sign in to comment.