From 28e773f9a75c686d5f9d8cee88fcf5a9eb944b20 Mon Sep 17 00:00:00 2001 From: mdipierro Date: Tue, 23 Oct 2012 10:11:33 -0500 Subject: [PATCH] utils compiles with python 3 --- VERSION | 2 +- gluon/utils.py | 36 +++++++++++++++++++++++++++--------- 2 files changed, 28 insertions(+), 10 deletions(-) diff --git a/VERSION b/VERSION index 2fc3e7fb..3c945c5e 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -Version 2.2.1 (2012-10-23 09:54:01) stable +Version 2.2.1 (2012-10-23 10:11:28) stable diff --git a/gluon/utils.py b/gluon/utils.py index 3ef03909..df629463 100644 --- a/gluon/utils.py +++ b/gluon/utils.py @@ -21,20 +21,32 @@ import os import re import logging import socket -import cPickle import base64 import zlib +try: + import cPickle as pickle # python 2 +except ImportError: + import pickle # python 3 + + try: from Crypto.Cipher import AES except ImportError: - from contrib import aes as AES + try: + from .aes import AES + except ImportError: + from contrib.aes import AES try: from contrib.pbkdf2 import pbkdf2_hex HAVE_PBKDF2 = True except ImportError: - HAVE_PBKDF2 = False + try: + from .pbkdf2 import pbkdf2_hex + HAVE_PBKDF2 = True + except (ImportError, ValueError): + HAVE_PBKDF2 = False logger = logging.getLogger("web2py") @@ -115,7 +127,7 @@ def pad(s, n=32, padchar='.'): def secure_dumps(data, encryption_key, hash_key=None, compression_level=None): if not hash_key: hash_key = hashlib.sha1(encryption_key).hexdigest() - dump = cPickle.dumps(data) + dump = pickle.dumps(data) if compression_level: dump = zlib.compress(dump, compression_level) key = pad(encryption_key[:32]) @@ -141,8 +153,8 @@ def secure_loads(data, encryption_key, hash_key=None, compression_level=None): data = data.rstrip(' ') if compression_level: data = zlib.decompress(data) - return cPickle.loads(data) - except (TypeError, cPickle.UnpicklingError): + return pickle.loads(data) + except (TypeError, pickle.UnpicklingError): return None ### compute constant CTOKENS @@ -173,7 +185,10 @@ def initialize_urandom(): # try to add process-specific entropy frandom = open('/dev/urandom', 'wb') try: - frandom.write(''.join(chr(t) for t in ctokens)) + try: + frandom.write(''.join(chr(t) for t in ctokens)) # python 2 + except: + frandom.write(bytes([]).join(bytes([t]) for t in ctokens)) # python 3 finally: frandom.close() except IOError: @@ -185,8 +200,11 @@ def initialize_urandom(): """Cryptographically secure session management is not possible on your system because your system does not provide a cryptographically secure entropy source. This is not specific to web2py; consider deploying on a different operating system.""") - unpacked_ctokens = struct.unpack('=QQ', string.join( - (chr(x) for x in ctokens), '')) + try: + packed = ''.join(chr(x) for x in ctokens) # python 2 + except: + packed = bytes([]).join(bytes([x]) for x in ctokens) # python 3 + unpacked_ctokens = struct.unpack('=QQ', packed) return unpacked_ctokens, have_urandom UNPACKED_CTOKENS, HAVE_URANDOM = initialize_urandom()