Python 2.7 和 3.X 兼容性

1 datetime.utcnow()

datetime.utcnow() 在 Python 3.12+ 中已被移除

修复方案: 将所有 datetime.utcnow() 替换为 datetime.now()

2 secrets 模块

try:
    import secrets
except ImportError:
    # Python 2.7 没有 secrets 模块,提供兼容实现
    class _Secrets(object):
        @staticmethod
        def token_hex(nbytes):
            return ''.join(random.choice('0123456789abcdef') for _ in range(nbytes * 2))

        @staticmethod
        def token_urlsafe(nbytes):
            alphabet = string.ascii_letters + string.digits + '-_'
            return ''.join(random.choice(alphabet) for _ in range(nbytes))

    secrets = _Secrets()

Last updated