|
| 1 | +import base64 |
| 2 | +import os |
| 3 | +import uuid |
| 4 | + |
| 5 | +try: # use unicode-slugify library if installed |
| 6 | + from slugify import slugify |
| 7 | + |
| 8 | + SLUGIFY_KWARGS = dict(only_ascii=True) |
| 9 | +except ImportError: |
| 10 | + from django.utils.text import slugify |
| 11 | + |
| 12 | + SLUGIFY_KWARGS = dict(allow_unicode=False) |
| 13 | + |
| 14 | + |
| 15 | +class FilePattern: |
| 16 | + """ |
| 17 | + Write advanced filename patterns using the Format Specification Mini-Language. |
| 18 | +
|
| 19 | + Basic example: |
| 20 | +
|
| 21 | + .. code-block:: python |
| 22 | +
|
| 23 | + from django.db import models |
| 24 | + from dynamic_names import FilePattern |
| 25 | +
|
| 26 | + upload_to_pattern = FilePattern('{app_name:.25}/{model_name:.30}/{uuid_base32}{ext}') |
| 27 | +
|
| 28 | + class FileModel(models.Model): |
| 29 | + my_file = models.FileField(upload_to=upload_to_pattern) |
| 30 | +
|
| 31 | + Args: |
| 32 | +
|
| 33 | + ext: File extension including the dot. |
| 34 | + name: Filename excluding the folders. |
| 35 | + model_name: Name of the Django model. |
| 36 | + app_label: App label of the Django model. |
| 37 | + uuid_base16: Base16 (hex) representation of a UUID. |
| 38 | + uuid_base32: Base32 representation of a UUID. |
| 39 | + uuid_base64: Base64 representation of a UUID. Not supported by all file systems. |
| 40 | + slug: Auto created slug based on another field on the model instance. |
| 41 | + slug_from: Name of the field the slug should be populated from. |
| 42 | +
|
| 43 | +
|
| 44 | + Auto slug example: |
| 45 | +
|
| 46 | + .. code-block:: python |
| 47 | +
|
| 48 | + from django.db import models |
| 49 | + from dynamic_names import FilePattern |
| 50 | +
|
| 51 | + class SlugPattern(FilePattern): |
| 52 | + filename_pattern = '{app_name:.25}/{model_name:.30}/{slug}{ext}' |
| 53 | +
|
| 54 | + class FileModel(models.Model): |
| 55 | + title = models.CharField(max_length=100) |
| 56 | + my_file = models.FileField(upload_to=SlugPattern(slug_from='title')) |
| 57 | +
|
| 58 | + """ |
| 59 | + |
| 60 | + slug_from = None |
| 61 | + |
| 62 | + filename_pattern = '{name}{ext}' |
| 63 | + |
| 64 | + def __call__(self, instance, filename): |
| 65 | + """Return filename based for given instance and filename.""" |
| 66 | + # UUID needs to be set on call, not per instance to avoid state leakage. |
| 67 | + guid = self.get_uuid() |
| 68 | + path, ext = os.path.splitext(filename) |
| 69 | + path, name = os.path.split(path) |
| 70 | + defaults = { |
| 71 | + 'ext': ext, |
| 72 | + 'name': name, |
| 73 | + 'model_name': instance._meta.model_name, |
| 74 | + 'app_label': instance._meta.app_label, |
| 75 | + 'uuid_base10': self.uuid_2_base10(guid), |
| 76 | + 'uuid_base16': self.uuid_2_base16(guid), |
| 77 | + 'uuid_base32': self.uuid_2_base32(guid), |
| 78 | + 'uuid_base64': self.uuid_2_base64(guid), |
| 79 | + } |
| 80 | + defaults.update(self.override_values) |
| 81 | + if self.slug_from is not None: |
| 82 | + field_value = getattr(instance, self.slug_from) |
| 83 | + defaults['slug'] = slugify(field_value, **SLUGIFY_KWARGS) |
| 84 | + return self.filename_pattern.format(**defaults) |
| 85 | + |
| 86 | + def __init__(self, **kwargs): |
| 87 | + self.kwargs = kwargs |
| 88 | + override_values = kwargs.copy() |
| 89 | + self.slug_from = override_values.pop('slug_from', self.slug_from) |
| 90 | + self.filename_pattern = override_values.pop('filename_pattern', self.filename_pattern) |
| 91 | + self.override_values = override_values |
| 92 | + |
| 93 | + def deconstruct(self): |
| 94 | + """Destruct callable to support Django migrations.""" |
| 95 | + path = "%s.%s" % (self.__class__.__module__, self.__class__.__name__) |
| 96 | + return path, [], self.kwargs |
| 97 | + |
| 98 | + @staticmethod |
| 99 | + def get_uuid(): |
| 100 | + """Return UUID version 4.""" |
| 101 | + return uuid.uuid4() |
| 102 | + |
| 103 | + @staticmethod |
| 104 | + def uuid_2_base10(uuid): |
| 105 | + """Return 39 digits long integer UUID as Base10.""" |
| 106 | + return uuid.int |
| 107 | + |
| 108 | + @staticmethod |
| 109 | + def uuid_2_base16(uuid): |
| 110 | + """Return 32 char long UUID as Base16 (hex).""" |
| 111 | + return uuid.hex |
| 112 | + |
| 113 | + @staticmethod |
| 114 | + def uuid_2_base32(uuid): |
| 115 | + """Return 27 char long UUIDv4 as Base32.""" |
| 116 | + return base64.b32encode( |
| 117 | + uuid.bytes |
| 118 | + ).decode('utf-8').rstrip('=\n') |
| 119 | + |
| 120 | + @staticmethod |
| 121 | + def uuid_2_base64(uuid): |
| 122 | + """ |
| 123 | + Return 23 char long UUIDv4 as Base64. |
| 124 | +
|
| 125 | + .. warning:: Not all file systems support Base64 file names. |
| 126 | + e.g. The Apple File System (APFS) is case insensitive by default. |
| 127 | +
|
| 128 | + """ |
| 129 | + return base64.urlsafe_b64encode( |
| 130 | + uuid.bytes |
| 131 | + ).decode('utf-8').rstrip('=\n') |
0 commit comments