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

Store file size into database table #24

Merged
merged 1 commit into from
Jan 31, 2023
Merged
Show file tree
Hide file tree
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# Generated by Django 4.1.5 on 2023-01-31 11:41

from django.db import migrations, models
import utilities.json


class Migration(migrations.Migration):

dependencies = [
('netbox_attachments', '0003_alter_netboxattachment_name'),
]

operations = [
migrations.AddField(
model_name='netboxattachment',
name='size',
field=models.PositiveBigIntegerField(blank=True, editable=False, null=True),
),
migrations.AlterField(
model_name='netboxattachment',
name='custom_field_data',
field=models.JSONField(blank=True, default=dict, encoder=utilities.json.CustomFieldJSONEncoder),
),
]
30 changes: 12 additions & 18 deletions netbox_attachments/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,12 @@ class NetBoxAttachment(NetBoxModel):
file = models.FileField(
upload_to=attachment_upload,
)
size = models.PositiveBigIntegerField(
editable=False,
null=True,
blank=True,
help_text='Size of the file in bytes',
)
name = models.CharField(
max_length=254,
blank=True
Expand Down Expand Up @@ -63,24 +69,12 @@ def delete(self, *args, **kwargs):
# before the request finishes. (For example, to display a message indicating the ImageAttachment was deleted.)
self.file.name = _name

@property
def size(self):
"""
Wrapper around `file.size` to suppress an OSError in case the file is inaccessible. Also opportunistically
catch other exceptions that we know other storage back-ends to throw.
"""
expected_exceptions = [OSError]

try:
from botocore.exceptions import ClientError
expected_exceptions.append(ClientError)
except ImportError:
pass

try:
return self.file.size
except tuple(expected_exceptions):
return None
def save(self, *args, **kwargs):
if self.file:
if not self.name:
self.name = self.file.name.rsplit('/', 1)[-1]
self.size = self.file.size
super().save(*args, **kwargs)

def to_objectchange(self, action):
objectchange = super().to_objectchange(action)
Expand Down
2 changes: 1 addition & 1 deletion netbox_attachments/version.py
Original file line number Diff line number Diff line change
@@ -1 +1 @@
__version__ = "1.0.6"
__version__ = "1.1.0"