ManualVariationsModel   A
last analyzed

Complexity

Total Complexity 0

Size/Duplication

Total Lines 6
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 0
c 0
b 0
f 0
dl 0
loc 6
rs 10
1
from io import BytesIO
2
3
from django.core.files.base import ContentFile
4
from django.core.files.storage import FileSystemStorage
5
from django.db import models
6
from django.db.models.signals import post_delete, pre_save
7
from PIL import Image
8
9
from stdimage import StdImageField
10
from stdimage.models import StdImageFieldFile
11
from stdimage.utils import (
12
    UploadTo, UploadToAutoSlugClassNameDir, UploadToUUID,
13
    pre_delete_delete_callback, pre_save_delete_callback, render_variations
14
)
15
from stdimage.validators import MaxSizeValidator, MinSizeValidator
16
17
18
class SimpleModel(models.Model):
19
    """works as ImageField"""
20
    image = StdImageField(upload_to='img/')
21
22
23
class AdminDeleteModel(models.Model):
24
    """can be deleted through admin"""
25
    image = StdImageField(
26
        upload_to=UploadTo(name='image', path='img'),
27
        blank=True
28
    )
29
30
31
class ResizeModel(models.Model):
32
    """resizes image to maximum size to fit a 640x480 area"""
33
    image = StdImageField(
34
        upload_to=UploadTo(name='image', path='img'),
35
        variations={
36
            'medium': {'width': 400, 'height': 400},
37
            'thumbnail': (100, 75),
38
        }
39
    )
40
41
42
class ResizeCropModel(models.Model):
43
    """resizes image to 640x480 cropping if necessary"""
44
    image = StdImageField(
45
        upload_to=UploadTo(name='image', path='img'),
46
        variations={'thumbnail': (150, 150, True)}
47
    )
48
49
50
class ThumbnailModel(models.Model):
51
    """creates a thumbnail resized to maximum size to fit a 100x75 area"""
52
    image = StdImageField(
53
        upload_to=UploadTo(name='image', path='img'),
54
        blank=True,
55
        variations={'thumbnail': (100, 75)}
56
    )
57
58
59
class MaxSizeModel(models.Model):
60
    image = StdImageField(
61
        upload_to=UploadTo(name='image', path='img'),
62
        validators=[MaxSizeValidator(16, 16)]
63
    )
64
65
66
class MinSizeModel(models.Model):
67
    image = StdImageField(
68
        upload_to=UploadTo(name='image', path='img'),
69
        validators=[MinSizeValidator(200, 200)]
70
    )
71
72
73
class ForceMinSizeModel(models.Model):
74
    """creates a thumbnail resized to maximum size to fit a 100x75 area"""
75
    image = StdImageField(
76
        upload_to=UploadTo(name='image', path='img'),
77
        force_min_size=True,
78
        variations={'thumbnail': (600, 600)}
79
    )
80
81
82
class AutoSlugClassNameDirModel(models.Model):
83
    name = models.CharField(max_length=50)
84
    image = StdImageField(
85
        upload_to=UploadToAutoSlugClassNameDir(populate_from='name')
86
    )
87
88
89
class UUIDModel(models.Model):
90
    image = StdImageField(upload_to=UploadToUUID(path='img'))
91
92
93
class CustomManager(models.Manager):
94
    """Just like Django's default, but a different class."""
95
    pass
96
97
98
class CustomManagerModel(models.Model):
99
    customer_manager = CustomManager()
100
101
    class Meta:
102
        abstract = True
103
104
105
class ManualVariationsModel(CustomManagerModel):
106
    """delays creation of 150x150 thumbnails until it is called manually"""
107
    image = StdImageField(
108
        upload_to=UploadTo(name='image', path='img'),
109
        variations={'thumbnail': (150, 150, True)},
110
        render_variations=False
111
    )
112
113
114
class MyStorageModel(CustomManagerModel):
115
    """delays creation of 150x150 thumbnails until it is called manually"""
116
    image = StdImageField(
117
        upload_to=UploadTo(name='image', path='img'),
118
        variations={'thumbnail': (150, 150, True)},
119
        storage=FileSystemStorage(),
120
    )
121
122
123
def render_job(**kwargs):
124
    render_variations(**kwargs)
125
    return False
126
127
128
class UtilVariationsModel(models.Model):
129
    """delays creation of 150x150 thumbnails until it is called manually"""
130
    image = StdImageField(
131
        upload_to=UploadTo(name='image', path='img'),
132
        variations={'thumbnail': (150, 150, True)},
133
        render_variations=render_job
134
    )
135
136
137
class ThumbnailWithoutDirectoryModel(models.Model):
138
    """Save into a generated filename that does not contain any '/' char"""
139
    image = StdImageField(
140
        upload_to=lambda instance, filename: 'custom.gif',
141
        variations={'thumbnail': {'width': 150, 'height': 150}},
142
    )
143
144
145
def custom_render_variations(file_name, variations, storage, replace=False):
146
    """Resize image to 100x100."""
147
    for _, variation in variations.items():
148
        variation_name = StdImageFieldFile.get_variation_name(
149
            file_name,
150
            variation['name']
151
        )
152
        if storage.exists(variation_name):
153
            storage.delete(variation_name)
154
155
        with storage.open(file_name) as f:
156
            with Image.open(f) as img:
157
                size = 100, 100
158
                img = img.resize(size)
159
160
                with BytesIO() as file_buffer:
161
                    img.save(file_buffer, 'JPEG')
162
                    f = ContentFile(file_buffer.getvalue())
163
                    storage.save(variation_name, f)
164
165
    return False
166
167
168
class CustomRenderVariationsModel(models.Model):
169
    """Use custom render_variations."""
170
171
    image = StdImageField(
172
        upload_to=UploadTo(name='image', path='img'),
173
        variations={'thumbnail': (150, 150)},
174
        render_variations=custom_render_variations,
175
    )
176
177
178
post_delete.connect(pre_delete_delete_callback, sender=SimpleModel)
179
pre_save.connect(pre_save_delete_callback, sender=AdminDeleteModel)
180