~openerp-community/openerp-tools/yolanda.robla-openerp-server

« back to all changes in this revision

Viewing changes to openerp/tools/misc.py

  • Committer: Vo Minh Thu
  • Date: 2011-02-08 15:01:49 UTC
  • mfrom: (3346.1.6 server-lib)
  • Revision ID: vmt@openerp.com-20110208150149-x4vu09aj42ezma5a
[MERGE] merge of the openerp python module branch.

Show diffs side-by-side

added added

removed removed

Lines of Context:
55
55
except ImportError:
56
56
    html2text = None
57
57
 
58
 
import netsvc
 
58
import openerp.loglevels as loglevels
59
59
from config import config
60
60
from lru import LRU
61
61
 
 
62
# get_encodings, ustr and exception_to_unicode were originally from tools.misc.
 
63
# There are moved to loglevels until we refactor tools.
 
64
from openerp.loglevels import get_encodings, ustr, exception_to_unicode
 
65
 
62
66
_logger = logging.getLogger('tools')
63
67
 
64
68
# List of etree._Element subclasses that we choose to ignore when parsing XML.
67
71
 
68
72
# initialize a database with base/base.sql
69
73
def init_db(cr):
70
 
    import addons
 
74
    import openerp.addons as addons
71
75
    f = addons.get_module_resource('base', 'base.sql')
72
76
    base_sql_file = file_open(f)
73
77
    try:
200
204
 
201
205
    @return: fileobject if pathinfo is False else (fileobject, filepath)
202
206
    """
203
 
    import addons
 
207
    import openerp.addons as addons
204
208
    adps = addons.ad_paths
205
209
    rtp = os.path.normcase(os.path.abspath(config['root_path']))
206
210
 
434
438
    """
435
439
    class WriteToLogger(object):
436
440
        def __init__(self):
437
 
            self.logger = netsvc.Logger()
 
441
            self.logger = loglevels.Logger()
438
442
 
439
443
        def write(self, s):
440
 
            self.logger.notifyChannel('email_send', netsvc.LOG_DEBUG, s)
 
444
            self.logger.notifyChannel('email_send', loglevels.LOG_DEBUG, s)
441
445
 
442
446
    if openobject_id:
443
447
        message['Message-Id'] = generate_tracking_message_id(openobject_id)
841
845
def to_xml(s):
842
846
    return s.replace('&','&amp;').replace('<','&lt;').replace('>','&gt;')
843
847
 
844
 
def get_encodings(hint_encoding='utf-8'):
845
 
    fallbacks = {
846
 
        'latin1': 'latin9',
847
 
        'iso-8859-1': 'iso8859-15',
848
 
        'cp1252': '1252',
849
 
    }
850
 
    if hint_encoding:
851
 
        yield hint_encoding
852
 
        if hint_encoding.lower() in fallbacks:
853
 
            yield fallbacks[hint_encoding.lower()]
854
 
 
855
 
    # some defaults (also taking care of pure ASCII)
856
 
    for charset in ['utf8','latin1']:
857
 
        if not (hint_encoding) or (charset.lower() != hint_encoding.lower()):
858
 
            yield charset
859
 
 
860
 
    from locale import getpreferredencoding
861
 
    prefenc = getpreferredencoding()
862
 
    if prefenc and prefenc.lower() != 'utf-8':
863
 
        yield prefenc
864
 
        prefenc = fallbacks.get(prefenc.lower())
865
 
        if prefenc:
866
 
            yield prefenc
867
 
 
868
 
 
869
 
def ustr(value, hint_encoding='utf-8'):
870
 
    """This method is similar to the builtin `str` method, except
871
 
       it will return unicode() string.
872
 
 
873
 
    @param value: the value to convert
874
 
    @param hint_encoding: an optional encoding that was detected
875
 
                          upstream and should be tried first to
876
 
                          decode ``value``.
877
 
 
878
 
    @rtype: unicode
879
 
    @return: unicode string
880
 
    """
881
 
    if isinstance(value, Exception):
882
 
        return exception_to_unicode(value)
883
 
 
884
 
    if isinstance(value, unicode):
885
 
        return value
886
 
 
887
 
    if not isinstance(value, basestring):
888
 
        try:
889
 
            return unicode(value)
890
 
        except Exception:
891
 
            raise UnicodeError('unable to convert %r' % (value,))
892
 
 
893
 
    for ln in get_encodings(hint_encoding):
894
 
        try:
895
 
            return unicode(value, ln)
896
 
        except Exception:
897
 
            pass
898
 
    raise UnicodeError('unable to convert %r' % (value,))
899
 
 
900
 
 
901
 
def exception_to_unicode(e):
902
 
    if (sys.version_info[:2] < (2,6)) and hasattr(e, 'message'):
903
 
        return ustr(e.message)
904
 
    if hasattr(e, 'args'):
905
 
        return "\n".join((ustr(a) for a in e.args))
906
 
    try:
907
 
        return ustr(e)
908
 
    except Exception:
909
 
        return u"Unknown message"
910
 
 
911
 
 
912
848
# to be compatible with python 2.4
913
849
import __builtin__
914
850
if not hasattr(__builtin__, 'all'):
1077
1013
    return "%0.2f %s" % (s, units[i])
1078
1014
 
1079
1015
def logged(f):
1080
 
    from tools.func import wraps
 
1016
    from func import wraps
1081
1017
 
1082
1018
    @wraps(f)
1083
1019
    def wrapper(*args, **kwargs):
1094
1030
 
1095
1031
        vector.append('  result: %s' % pformat(res))
1096
1032
        vector.append('  time delta: %s' % (time.time() - timeb4))
1097
 
        netsvc.Logger().notifyChannel('logged', netsvc.LOG_DEBUG, '\n'.join(vector))
 
1033
        loglevels.Logger().notifyChannel('logged', loglevels.LOG_DEBUG, '\n'.join(vector))
1098
1034
        return res
1099
1035
 
1100
1036
    return wrapper
1104
1040
        self.fname = fname
1105
1041
 
1106
1042
    def __call__(self, f):
1107
 
        from tools.func import wraps
 
1043
        from func import wraps
1108
1044
 
1109
1045
        @wraps(f)
1110
1046
        def wrapper(*args, **kwargs):
1300
1236
    try:
1301
1237
        import pytz
1302
1238
    except Exception:
1303
 
        netsvc.Logger().notifyChannel("detect_server_timezone", netsvc.LOG_WARNING,
 
1239
        loglevels.Logger().notifyChannel("detect_server_timezone", loglevels.LOG_WARNING,
1304
1240
            "Python pytz module is not available. Timezone will be set to UTC by default.")
1305
1241
        return 'UTC'
1306
1242
 
1334
1270
        if value:
1335
1271
            try:
1336
1272
                tz = pytz.timezone(value)
1337
 
                netsvc.Logger().notifyChannel("detect_server_timezone", netsvc.LOG_INFO,
 
1273
                loglevels.Logger().notifyChannel("detect_server_timezone", loglevels.LOG_INFO,
1338
1274
                    "Using timezone %s obtained from %s." % (tz.zone,source))
1339
1275
                return value
1340
1276
            except pytz.UnknownTimeZoneError:
1341
 
                netsvc.Logger().notifyChannel("detect_server_timezone", netsvc.LOG_WARNING,
 
1277
                loglevels.Logger().notifyChannel("detect_server_timezone", loglevels.LOG_WARNING,
1342
1278
                    "The timezone specified in %s (%s) is invalid, ignoring it." % (source,value))
1343
1279
 
1344
 
    netsvc.Logger().notifyChannel("detect_server_timezone", netsvc.LOG_WARNING,
 
1280
    loglevels.Logger().notifyChannel("detect_server_timezone", loglevels.LOG_WARNING,
1345
1281
        "No valid timezone could be detected, using default UTC timezone. You can specify it explicitly with option 'timezone' in the server configuration.")
1346
1282
    return 'UTC'
1347
1283