Skip to content

Commit 0d25f7e

Browse files
committed
v1.0 changes
1 parent 08992d5 commit 0d25f7e

File tree

6 files changed

+59
-22
lines changed

6 files changed

+59
-22
lines changed

README.md

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,18 @@
11
# PyMODM-ImageFileField
22
ImageFileField for PyMODM
33

4+
Configuration Media Path and Media Url
5+
```
6+
import imagefilefield
7+
8+
# Required
9+
imagefilefield.FILEFIELD_MEDIA_PATH = os.path.join(BASE_DIR, "media/")
10+
# Optional
11+
imagefilefield.FILEFIELD_MEDIA_URL = "/media/" # Default Value
12+
13+
```
14+
15+
416
```
517
from os.path import join
618
@@ -19,8 +31,7 @@ class TestImage(MongoModel):
1931
text = fields.CharField()
2032
image = ImageFileField(
2133
upload_to=join(MEDIA_ROOT, "test_image/%Y/%m/%d/"),
22-
blank=True,
23-
media_url=join(MEDIA_URL, "test_image/%Y/%m/%d/"))
34+
blank=True)
2435
# using custom size
2536
image2 = ImageFileField(
2637
upload_to=join(MEDIA_ROOT, "test_image/%Y/%m/%d/"),
@@ -29,8 +40,7 @@ class TestImage(MongoModel):
2940
"small": {"size": (200, 100), "smartcrop": True},
3041
"medium": {"size": (525, 625), "smartcrop": True},
3142
"big": {"size": (700, 700), "smartcrop": True}
32-
}
33-
media_url=join(MEDIA_URL, "test_image/%Y/%m/%d/"))
43+
})
3444
created = fields.DateTimeField(default=timezone.now)
3545
3646
```

imagefilefield/__init__.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
FILEFIELD_MEDIA_PATH = None
2+
FILEFIELD_MEDIA_URL = "/media/"

imagefilefield/fields.py

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,41 @@
11
from pymodm.fields import ImageField
22

33
from imagefilefield.files import ImageFieldToFile
4+
import imagefilefield
45

56

67
class ImageFileField(ImageField):
78
_wrapper_class = ImageFieldToFile
89

10+
@property
11+
def base_media_path(self):
12+
return imagefilefield.FILEFIELD_MEDIA_PATH
13+
14+
@property
15+
def base_media_url(self):
16+
return imagefilefield.FILEFIELD_MEDIA_URL
17+
918
def __init__(self, *args, **kwargs):
1019
# add custom params upload_to
1120
if not kwargs.get("upload_to"):
1221
raise ValueError("upload_to params is required")
1322
self.upload_to = kwargs.pop("upload_to")
1423
self.image_sizes = kwargs.pop("image_sizes", None)
15-
self.media_url = kwargs.pop("media_url", "/media/")
1624
super().__init__(*args, **kwargs)
1725

1826
def to_mongo(self, value):
1927
file_obj = self.to_python(value)
2028
# Save the file and return its name.
2129
if not file_obj._committed:
30+
if not self.base_media_path:
31+
raise ValueError("imagefilefield.FILEFIELD_MEDIA_PATH cannot be none")
32+
2233
file_obj.save(value.file_id, value)
2334

35+
# load saved gridfs files data from storage
36+
# for make the data available to next process
37+
file_obj.file = file_obj.storage.open(file_obj.file_id)
38+
2439
# create image with specific sizes settings
2540
file_obj.create_image_sizes()
2641

imagefilefield/files.py

Lines changed: 22 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
from os import path, makedirs
22
from typing import Tuple, Union
33
from io import BytesIO
4-
from datetime import datetime
54

65
from PIL import Image
76
from pymodm.files import ImageFieldFile
@@ -11,31 +10,39 @@
1110

1211
class ImageFieldToFile(ImageFieldFile):
1312

13+
def generate_image_path(self, key_size, base_path):
14+
'''
15+
return full image path
16+
'''
17+
media_path = path.join(
18+
base_path,
19+
self.field.upload_to,
20+
"{}_{}.{}".format(key_size, str(self.file_id), self.image.format.lower()))
21+
media_path = ("{:%s}" % (media_path)).format(self.file.uploadDate)
22+
return media_path
23+
1424
@property
1525
def images(self):
26+
'''
27+
return url created images base on defined sizes
28+
'''
1629
sizes = self.get_sizes
17-
media_url = self.field.media_url
1830
images = {}
1931

2032
for key in sizes.keys():
21-
media_path = path.join(
22-
media_url,
23-
"{}_{}.{}".format(key, str(self.file_id), self.image.format.lower()))
24-
media_path = ("{:%s}" % (media_path)).format(self.file.uploadDate)
25-
images[key] = media_path
33+
images[key] = self.generate_image_path(key, self.field.base_media_url)
2634
return images
2735

2836
@property
2937
def get_sizes(self):
38+
'''
39+
return the specified image sizes
40+
'''
3041
return self.field.image_sizes or getattr(self.instance, "IMAGE_SIZES", None)
3142

3243
def create_image_path(self, key: str) -> str:
3344
# file path
34-
fpath = path.join(
35-
self.field.upload_to,
36-
"{}_{}.{}".format(key, str(self.file_id), self.image.format.lower()))
37-
fpath = "{:%s}" % (fpath)
38-
fpath = fpath.format(datetime.utcnow())
45+
fpath = self.generate_image_path(key, self.field.base_media_path)
3946
# try create folder path if not exists
4047
folder_path = "/".join(fpath.split("/")[:-1])
4148
try:
@@ -46,16 +53,17 @@ def create_image_path(self, key: str) -> str:
4653
return fpath
4754

4855
def image_to_file(self, key: str, size: Tuple[int, int],
49-
image_path: str=None, smartcrop: bool = False) -> str:
56+
image_path: Union[BytesIO, str, None]=None,
57+
smartcrop: bool = False) -> str:
5058
'''
5159
method for convert image to desired size
5260
image: image binary file or image buffer
5361
size: (width, height)
5462
smart_crop: if not active will only use PIL `thumbnail` resizer
5563
'''
5664
fpath = self.create_image_path(key)
65+
5766
# image data could be path file or BytesIo data
58-
image_data: Union[BytesIO, str]
5967
if image_path:
6068
image_data = image_path
6169
else:

imagefilefield/smartcrop.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,5 +37,7 @@ def smart_crop(image, target_width, target_height, destination, do_resize):
3737

3838
crop_pos = exact_crop(center, width, height, target_width, target_height)
3939

40-
cropped = original[int(crop_pos['top']): int(crop_pos['bottom']), int(crop_pos['left']): int(crop_pos['right'])]
40+
cropped = original[
41+
int(crop_pos['top']): int(crop_pos['bottom']),
42+
int(crop_pos['left']): int(crop_pos['right'])]
4143
cv2.imwrite(destination, cropped)

setup.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
from setuptools import setup
22

33
setup(name='PYMODM-IMAGEFILEFIELD',
4-
version='0.1',
4+
version='1.0',
55
description='ImageFileField for PyMODM module',
66
url='https://github.com/weiztech/PyMODM-ImageFileField',
77
author='Jensen',
@@ -13,4 +13,4 @@
1313
'opencv-python>=3.4.0.12'
1414
],
1515
keywords='ImageFileField PyMODM-ImageFileField',
16-
zip_safe=False)
16+
zip_safe=False)

0 commit comments

Comments
 (0)