|
5 | 5 |
|
6 | 6 |
|
7 | 7 | def order_name(name):
|
8 |
| - """order_name -- Limit the name to 20 chars length, and convert to a |
9 |
| - ellipsed string. |
| 8 | + """order_name -- Limit a text to 20 chars length, if necessary strips the |
| 9 | + middle of the text and substitute it for an ellipsis. |
10 | 10 |
|
11 | 11 | name -- text to be limited.
|
12 | 12 |
|
13 | 13 | """
|
14 | 14 | name = re.sub(r'^.*/', '', name)
|
15 |
| - if len(name)>20: |
16 |
| - return name[:10] + "..." + name[-7:] |
17 |
| - else: |
| 15 | + if len(name) <= 20: |
18 | 16 | return name
|
| 17 | + return name[:10] + "..." + name[-7:] |
19 | 18 |
|
20 | 19 |
|
21 |
| -def serialize(instance): |
22 |
| - """serialize -- Serialize a Picture instance into a `json` object. |
| 20 | +def serialize(instance, file_attr='file'): |
| 21 | + """serialize -- Serialize a Picture instance into a dict. |
23 | 22 |
|
24 | 23 | instance -- Picture instance
|
| 24 | + file_attr -- attribute name that contains the FileField or ImageField |
| 25 | +
|
25 | 26 | """
|
| 27 | + obj = getattr(instance, file_attr) |
26 | 28 | return {
|
27 |
| - 'url': instance.file.url, |
28 |
| - 'name': order_name(instance.file.name), |
29 |
| - 'type': mimetypes.guess_type(instance.file.path)[0] or 'image/png', |
30 |
| - 'thumbnailUrl': instance.file.url, |
31 |
| - 'size': instance.file.size, |
| 29 | + 'url': obj.url, |
| 30 | + 'name': order_name(obj.name), |
| 31 | + 'type': mimetypes.guess_type(obj.path)[0] or 'image/png', |
| 32 | + 'thumbnailUrl': obj.url, |
| 33 | + 'size': obj.size, |
32 | 34 | 'deleteUrl': reverse('upload-delete', args=[instance.pk]),
|
33 | 35 | 'deleteType': 'DELETE',
|
34 | 36 | }
|
|
0 commit comments