Skip to content

Commit

Permalink
chore: isolate storage custom utilities
Browse files Browse the repository at this point in the history
  • Loading branch information
vncsna committed Feb 20, 2024
1 parent e8872a4 commit 99dd3cf
Show file tree
Hide file tree
Showing 7 changed files with 41 additions and 55 deletions.
8 changes: 4 additions & 4 deletions bd_api/apps/account/migrations/0001_initial.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@
from django.db import migrations, models

import bd_api.apps.account.models
import bd_api.apps.account.storage
import bd_api.apps.api.v1.validators
import bd_api.custom.storage


class Migration(migrations.Migration):
Expand Down Expand Up @@ -76,9 +76,9 @@ class Migration(migrations.Migration):
models.ImageField(
blank=True,
null=True,
storage=bd_api.apps.account.storage.OverwriteStorage(),
upload_to=bd_api.apps.account.models.image_path_and_rename,
validators=[bd_api.apps.api.v1.validators.validate_is_valid_image_format],
storage=bd_api.custom.storage.OverwriteStorage(),
upload_to=bd_api.custom.storage.upload_to,
validators=[bd_api.custom.storage.validate_image],
verbose_name="Imagem",
),
),
Expand Down
16 changes: 3 additions & 13 deletions bd_api/apps/account/models.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
import os
from typing import Tuple
from uuid import uuid4

Expand All @@ -15,18 +14,9 @@
from django.db.models.query import QuerySet
from django.utils import timezone

from bd_api.apps.account.storage import OverwriteStorage
from bd_api.apps.api.v1.validators import validate_is_valid_image_format
from bd_api.custom.graphql_jwt import ownership_required
from bd_api.custom.model import BaseModel


def image_path_and_rename(instance, filename):
"""Rename file to be the username"""
upload_to = instance.__class__.__name__.lower()
ext = filename.split(".")[-1]
filename = f"{instance.username}.{ext}"
return os.path.join(upload_to, filename)
from bd_api.custom.storage import OverwriteStorage, upload_to, validate_image


def split_password(password: str) -> Tuple[str, str, str, str]:
Expand Down Expand Up @@ -236,11 +226,11 @@ class Account(BaseModel, AbstractBaseUser, PermissionsMixin):
birth_date = models.DateField("Data de Nascimento", null=True, blank=True)
picture = models.ImageField(
"Imagem",
upload_to=image_path_and_rename,
null=True,
blank=True,
validators=[validate_is_valid_image_format],
storage=OverwriteStorage(),
upload_to=upload_to,
validators=[validate_image],
)
twitter = models.CharField("Twitter", max_length=255, null=True, blank=True)
linkedin = models.CharField("Linkedin", max_length=255, null=True, blank=True)
Expand Down
11 changes: 0 additions & 11 deletions bd_api/apps/account/storage.py

This file was deleted.

8 changes: 4 additions & 4 deletions bd_api/apps/api/v1/migrations/0001_initial.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,9 @@
from django.conf import settings
from django.db import migrations, models

import bd_api.apps.account.storage
import bd_api.apps.api.v1.models
import bd_api.apps.api.v1.validators
import bd_api.custom.storage


class Migration(migrations.Migration):
Expand Down Expand Up @@ -391,9 +391,9 @@ class Migration(migrations.Migration):
models.ImageField(
blank=True,
null=True,
storage=bd_api.apps.account.storage.OverwriteStorage(),
upload_to=bd_api.apps.api.v1.models.image_path_and_rename,
validators=[bd_api.apps.api.v1.validators.validate_is_valid_image_format],
storage=bd_api.custom.storage.OverwriteStorage(),
upload_to=bd_api.custom.storage.upload_to,
validators=[bd_api.custom.storage.validate_image],
verbose_name="Imagem",
),
),
Expand Down
17 changes: 3 additions & 14 deletions bd_api/apps/api/v1/models.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
# -*- coding: utf-8 -*-
import calendar
import json
import os
from collections import defaultdict
from datetime import datetime
from uuid import uuid4
Expand All @@ -13,10 +12,9 @@
from ordered_model.models import OrderedModel

from bd_api.apps.account.models import Account
from bd_api.apps.account.storage import OverwriteStorage
from bd_api.apps.api.v1.utils import check_kebab_case, check_snake_case
from bd_api.apps.api.v1.validators import validate_is_valid_image_format
from bd_api.custom.model import BaseModel
from bd_api.custom.storage import OverwriteStorage, upload_to, validate_image


def to_str(value: str | None, zfill: int = 0):
Expand All @@ -26,15 +24,6 @@ def to_str(value: str | None, zfill: int = 0):
return str(value).zfill(zfill)


def image_path_and_rename(instance, filename):
"""Rename file to be the username"""
upload_to = instance.__class__.__name__.lower()
ext = filename.split(".")[-1]
# get filename
filename = f"{instance.pk}.{ext}"
return os.path.join(upload_to, filename)


def get_date_time(date_times):
"""Returns a DateTimeRange object with the minimum start date and maximum end date"""
start_year, start_month, start_day = False, False, False
Expand Down Expand Up @@ -444,11 +433,11 @@ class Organization(BaseModel):
instagram = models.URLField(blank=True, null=True)
picture = models.ImageField(
"Imagem",
upload_to=image_path_and_rename,
null=True,
blank=True,
validators=[validate_is_valid_image_format],
storage=OverwriteStorage(),
upload_to=upload_to,
validators=[validate_image],
)

graphql_nested_filter_fields_whitelist = ["id"]
Expand Down
9 changes: 0 additions & 9 deletions bd_api/apps/api/v1/validators.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@

from django.conf import settings
from django.core.exceptions import ValidationError
from django.core.validators import FileExtensionValidator

current_site = os.getenv("url")

Expand Down Expand Up @@ -33,11 +32,3 @@ def validate_is_valid_area_key(
f"Area '{value}' is not valid. Area must valid.\
See {current_site}/schemas/bd_spatial_coverage_tree/ for valid areas."
)


def validate_is_valid_image_format(value):
"""Validate image file."""
validate_image_file_extension = FileExtensionValidator(
allowed_extensions=["jpg", "jpeg", "png", "gif"]
)
validate_image_file_extension(value)
27 changes: 27 additions & 0 deletions bd_api/custom/storage.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
# -*- coding: utf-8 -*-
from os.path import join
from typing import Any

from django.core.files.storage import get_storage_class
from django.core.validators import FileExtensionValidator


def upload_to(instance: Any, filename: str):
"""Get upload path as model primary key with extension"""
extension = filename.split(".")[-1]
folder = instance.__class__.__name__.lower()
return join(folder, f"{instance.pk}.{extension}")


def validate_image(file):
"""Check if image format is allowed"""
FileExtensionValidator(allowed_extensions=["jpg", "jpeg", "png"])(file)


class OverwriteStorage(get_storage_class()):
def _save(self, name, content):
self.delete(name)
return super(OverwriteStorage, self)._save(name, content)

def get_available_name(self, name, max_length=None):
return name

0 comments on commit 99dd3cf

Please sign in to comment.