Created
November 2, 2016 16:27
-
-
Save DarkRedman/54fa2a7b34ccc58a70c31ad1af88d29e to your computer and use it in GitHub Desktop.
A standalone version of django timesince
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from __future__ import unicode_literals | |
import calendar, datetime, six | |
from functools import total_ordering, wraps | |
class Promise(object): | |
""" | |
This is just a base class for the proxy class created in | |
the closure of the lazy function. It can be used to recognize | |
promises in code. | |
""" | |
pass | |
def lazy(func, *resultclasses): | |
""" | |
Turns any callable into a lazy evaluated callable. You need to give result | |
classes or types -- at least one is needed so that the automatic forcing of | |
the lazy evaluation code is triggered. Results are not memoized; the | |
function is evaluated on every access. | |
""" | |
@total_ordering | |
class __proxy__(Promise): | |
""" | |
Encapsulate a function call and act as a proxy for methods that are | |
called on the result of that function. The function is not evaluated | |
until one of the methods on the result is called. | |
""" | |
__prepared = False | |
def __init__(self, args, kw): | |
self.__args = args | |
self.__kw = kw | |
if not self.__prepared: | |
self.__prepare_class__() | |
self.__prepared = True | |
def __reduce__(self): | |
return ( | |
_lazy_proxy_unpickle, | |
(func, self.__args, self.__kw) + resultclasses | |
) | |
def __repr__(self): | |
return repr(self.__cast()) | |
@classmethod | |
def __prepare_class__(cls): | |
for resultclass in resultclasses: | |
for type_ in resultclass.mro(): | |
for method_name in type_.__dict__.keys(): | |
# All __promise__ return the same wrapper method, they | |
# look up the correct implementation when called. | |
if hasattr(cls, method_name): | |
continue | |
meth = cls.__promise__(method_name) | |
setattr(cls, method_name, meth) | |
cls._delegate_bytes = bytes in resultclasses | |
cls._delegate_text = six.text_type in resultclasses | |
assert not (cls._delegate_bytes and cls._delegate_text), ( | |
"Cannot call lazy() with both bytes and text return types.") | |
if cls._delegate_text: | |
if six.PY3: | |
cls.__str__ = cls.__text_cast | |
else: | |
cls.__unicode__ = cls.__text_cast | |
cls.__str__ = cls.__bytes_cast_encoded | |
elif cls._delegate_bytes: | |
if six.PY3: | |
cls.__bytes__ = cls.__bytes_cast | |
else: | |
cls.__str__ = cls.__bytes_cast | |
@classmethod | |
def __promise__(cls, method_name): | |
# Builds a wrapper around some magic method | |
def __wrapper__(self, *args, **kw): | |
# Automatically triggers the evaluation of a lazy value and | |
# applies the given magic method of the result type. | |
res = func(*self.__args, **self.__kw) | |
return getattr(res, method_name)(*args, **kw) | |
return __wrapper__ | |
def __text_cast(self): | |
return func(*self.__args, **self.__kw) | |
def __bytes_cast(self): | |
return bytes(func(*self.__args, **self.__kw)) | |
def __bytes_cast_encoded(self): | |
return func(*self.__args, **self.__kw).encode('utf-8') | |
def __cast(self): | |
if self._delegate_bytes: | |
return self.__bytes_cast() | |
elif self._delegate_text: | |
return self.__text_cast() | |
else: | |
return func(*self.__args, **self.__kw) | |
def __str__(self): | |
# object defines __str__(), so __prepare_class__() won't overload | |
# a __str__() method from the proxied class. | |
return str(self.__cast()) | |
def __ne__(self, other): | |
if isinstance(other, Promise): | |
other = other.__cast() | |
return self.__cast() != other | |
def __eq__(self, other): | |
if isinstance(other, Promise): | |
other = other.__cast() | |
return self.__cast() == other | |
def __lt__(self, other): | |
if isinstance(other, Promise): | |
other = other.__cast() | |
return self.__cast() < other | |
def __hash__(self): | |
return hash(self.__cast()) | |
def __mod__(self, rhs): | |
if self._delegate_bytes and six.PY2: | |
return bytes(self) % rhs | |
elif self._delegate_text: | |
return six.text_type(self) % rhs | |
return self.__cast() % rhs | |
def __deepcopy__(self, memo): | |
# Instances of this class are effectively immutable. It's just a | |
# collection of functions. So we don't need to do anything | |
# complicated for copying. | |
memo[id(self)] = self | |
return self | |
@wraps(func) | |
def __wrapper__(*args, **kw): | |
# Creates the proxy object, instead of the actual value. | |
return __proxy__(args, kw) | |
return __wrapper__ | |
def force_text(s, encoding='utf-8', strings_only=False, errors='strict'): | |
""" | |
Similar to smart_text, except that lazy instances are resolved to | |
strings, rather than kept as lazy objects. | |
If strings_only is True, don't convert (some) non-string-like objects. | |
""" | |
# Handle the common case first for performance reasons. | |
if issubclass(type(s), six.text_type): | |
return s | |
if strings_only and is_protected_type(s): | |
return s | |
try: | |
if not issubclass(type(s), six.string_types): | |
if six.PY3: | |
if isinstance(s, bytes): | |
s = six.text_type(s, encoding, errors) | |
else: | |
s = six.text_type(s) | |
elif hasattr(s, '__unicode__'): | |
s = six.text_type(s) | |
else: | |
s = six.text_type(bytes(s), encoding, errors) | |
else: | |
# Note: We use .decode() here, instead of six.text_type(s, encoding, | |
# errors), so that if s is a SafeBytes, it ends up being a | |
# SafeText at the end. | |
s = s.decode(encoding, errors) | |
except UnicodeDecodeError as e: | |
if not isinstance(s, Exception): | |
raise DjangoUnicodeDecodeError(s, *e.args) | |
else: | |
# If we get to here, the caller has passed in an Exception | |
# subclass populated with non-ASCII bytestring data without a | |
# working unicode method. Try to handle this without raising a | |
# further exception by individually forcing the exception args | |
# to unicode. | |
s = ' '.join(force_text(arg, encoding, strings_only, errors) | |
for arg in s) | |
return s | |
def ngettext(singular, plural, number): | |
if number == 1: | |
return singular | |
return plural | |
ngettext_lazy = ngettext | |
def ungettext(singular, plural, number): | |
return force_text(ngettext(singular, plural, number)) | |
def lazy_number(func, resultclass, number=None, **kwargs): | |
if isinstance(number, six.integer_types): | |
kwargs['number'] = number | |
proxy = lazy(func, resultclass)(**kwargs) | |
else: | |
original_kwargs = kwargs.copy() | |
class NumberAwareString(resultclass): | |
def __bool__(self): | |
return bool(kwargs['singular']) | |
def __nonzero__(self): # Python 2 compatibility | |
return type(self).__bool__(self) | |
def __mod__(self, rhs): | |
if isinstance(rhs, dict) and number: | |
try: | |
number_value = rhs[number] | |
except KeyError: | |
raise KeyError( | |
"Your dictionary lacks key '%s\'. Please provide " | |
"it, because it is required to determine whether " | |
"string is singular or plural." % number | |
) | |
else: | |
number_value = rhs | |
kwargs['number'] = number_value | |
translated = func(**kwargs) | |
try: | |
translated = translated % rhs | |
except TypeError: | |
# String doesn't contain a placeholder for the number | |
pass | |
return translated | |
proxy = lazy(lambda **kwargs: NumberAwareString(), NumberAwareString)(**kwargs) | |
proxy.__reduce__ = lambda: (_lazy_number_unpickle, (func, resultclass, number, original_kwargs)) | |
return proxy | |
def ungettext_lazy(singular, plural, number=None): | |
return lazy_number(ungettext, six.text_type, singular=singular, plural=plural, number=number) | |
def is_aware(d): | |
d.tzinfo is not None and d.tzinfo.utcoffset(d) is not None | |
TIMESINCE_CHUNKS = ( | |
(60 * 60 * 24 * 365, ungettext_lazy('%d year', '%d years')), | |
(60 * 60 * 24 * 30, ungettext_lazy('%d month', '%d months')), | |
(60 * 60 * 24 * 7, ungettext_lazy('%d week', '%d weeks')), | |
(60 * 60 * 24, ungettext_lazy('%d day', '%d days')), | |
(60 * 60, ungettext_lazy('%d hour', '%d hours')), | |
(60, ungettext_lazy('%d minute', '%d minutes')) | |
) | |
def timesince(d, now=None, reversed=False): | |
""" | |
Takes two datetime objects and returns the time between d and now | |
as a nicely formatted string, e.g. "10 minutes". If d occurs after now, | |
then "0 minutes" is returned. | |
Units used are years, months, weeks, days, hours, and minutes. | |
Seconds and microseconds are ignored. Up to two adjacent units will be | |
displayed. For example, "2 weeks, 3 days" and "1 year, 3 months" are | |
possible outputs, but "2 weeks, 3 hours" and "1 year, 5 days" are not. | |
Adapted from | |
http://web.archive.org/web/20060617175230/http://blog.natbat.co.uk/archive/2003/Jun/14/time_since | |
""" | |
# Convert datetime.date to datetime.datetime for comparison. | |
if not isinstance(d, datetime.datetime): | |
d = datetime.datetime(d.year, d.month, d.day) | |
if now and not isinstance(now, datetime.datetime): | |
now = datetime.datetime(now.year, now.month, now.day) | |
if not now: | |
now = datetime.datetime.now(utc if is_aware(d) else None) | |
delta = (d - now) if reversed else (now - d) | |
# Deal with leapyears by subtracing the number of leapdays | |
delta -= datetime.timedelta(calendar.leapdays(d.year, now.year)) | |
# ignore microseconds | |
since = delta.days * 24 * 60 * 60 + delta.seconds | |
if since <= 0: | |
# d is in the future compared to now, stop processing. | |
return avoid_wrapping(ugettext('0 minutes')) | |
for i, (seconds, name) in enumerate(TIMESINCE_CHUNKS): | |
count = since // seconds | |
if count != 0: | |
break | |
result = name % count | |
if i + 1 < len(TIMESINCE_CHUNKS): | |
# Now get the second item | |
seconds2, name2 = TIMESINCE_CHUNKS[i + 1] | |
count2 = (since - (seconds * count)) // seconds2 | |
if count2 != 0: | |
result += ', ' + name2 % count2 | |
return result | |
def timeuntil(d, now=None): | |
""" | |
Like timesince, but returns a string measuring the time until | |
the given time. | |
""" | |
return timesince(d, now, reversed=True) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment