Skip to content
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

feat(validators): add FileSizeValidator #51

Merged
merged 2 commits into from
Sep 25, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions sage_tools/validators/file.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
from django.core.exceptions import ValidationError

from sage_tools.utils.converters import UnitConvertor


class FileSizeValidator:
def __init__(self, max_size):
"""
Initialize the validator with the maximum file size.

Args:
max_size (int): Maximum file size in bytes.
"""
self.max_size = max_size

def __call__(self, value):
"""
Check the file size and raise a ValidationError if it exceeds the limit.

Args:
value (File): The file being uploaded.
"""
size = UnitConvertor.convert_byte_to_megabyte(self.max_size)
if value.size > self.max_size:
raise ValidationError(f"File size must not exceed {size} MB.")

def deconstruct(self):
"""
Deconstruct the validator for serialization.

Returns:
tuple: The full path of the object, positional arguments, and keyword arguments.
"""
path = f"{self.__module__}.{self.__class__.__name__}"
args = (self.max_size,)
kwargs = {}
return path, args, kwargs
Loading