| 16 | |
| 17 | |
| 18 | def humanize(obj, type=None, length=None): |
| 19 | if obj is None: |
| 20 | obj = '' |
| 21 | elif type and type.startswith('time'): |
| 22 | tz = type[len('time'):].lstrip('-') |
| 23 | tz = timezone(tz) if tz else getattr(current_app, 'timezone', '') or utc |
| 24 | obj = format_time(float(obj), tz) if obj else '' |
| 25 | elif type and type.startswith('natural-time'): |
| 26 | tz = type[len('natural-time'):].lstrip('-') |
| 27 | tz = timezone(tz) if tz else getattr(current_app, 'timezone', '') or utc |
| 28 | delta = datetime.now(tz) - datetime.fromtimestamp(float(obj), tz) |
| 29 | if delta < timedelta(days=1): |
| 30 | obj = naturaltime(delta) |
| 31 | else: |
| 32 | obj = format_time(float(obj), tz) if obj else '' |
| 33 | elif isinstance(obj, str) and not re.match(UUID_REGEX, obj): |
| 34 | obj = obj.replace('-', ' ').replace('_', ' ') |
| 35 | obj = re.sub('|'.join(KEYWORDS_UP), |
| 36 | lambda m: m.group(0).upper(), obj) |
| 37 | if obj and obj not in KEYWORDS_DOWN: |
| 38 | obj = obj[0].upper() + obj[1:] |
| 39 | elif isinstance(obj, list): |
| 40 | if all(isinstance(x, (int, float, str)) for x in obj): |
| 41 | obj = ', '.join(map(str, obj)) |
| 42 | if length is not None and len(obj) > length: |
| 43 | obj = obj[:length - 4] + ' ...' |
| 44 | return obj |