# vim:set expandtab tabstop=4 shiftwidth=4: """ Monkey-patch cookielib to fix bug preventing expiration dates far in the future. See: http://bugs.python.org/issue5537 Author: Alex Quinn - http://alexquinn.org License: Public Domain Usage: import monkey_patch_cookielib_time2isoz monkey_patch_cookielib_time2isoz() """ import cookielib import sys from datetime import datetime, timedelta def monkey_patch_cookielib_time2isoz(): try: cookielib.time2isoz(2**32) except ValueError: def time2isoz(t=None): if t is None: dt = datetime.now() else: dt = datetime.utcfromtimestamp(0) + timedelta(seconds=int(t)) return "%04d-%02d-%02d %02d:%02d:%02dZ"%\ (dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second) cookielib.time2isoz = time2isoz if __name__ == "__main__": def check_if_bug_exists(): t = 2**32 try: print(" Fixed: time2isoz(%r) --> %r"%(t, cookielib.time2isoz(t))) return True except ValueError: print(" Broken: time2isoz(%r) --> %r"%(t, sys.exc_info()[1])) # using exc_info() not `... as e` for compatibility with Python <=2.5 return False print("\nBefore patching:") check_if_bug_exists() is_fixed = monkey_patch_cookielib_time2isoz() # Bug has been confirmed on Linux 2.6.9 32-bit. It does *not* exist on # Python 32-bit running on Windows 7 64-bit. is_64_bit = getattr(sys, "maxsize", 0) > 2**32 is_linux = sys.platform == "linux2" assert not is_fixed or not is_linux or is_64_bit print("\nAfter patching:") is_fixed = check_if_bug_exists() # Bug should be fixed now, no matter what. assert is_fixed