#
##############################################################################
-#.apidoc title: Utilities: tools.misc
"""
Miscellaneous tools used by OpenERP.
import threading
import time
import zipfile
-from collections import defaultdict
+from collections import defaultdict, Mapping
from datetime import datetime
from itertools import islice, izip, groupby
from lxml import etree
from which import which
from threading import local
+import traceback
try:
from html2text import html2text
from config import config
from cache import *
+import openerp
# get_encodings, ustr and exception_to_unicode were originally from tools.misc.
# There are moved to loglevels until we refactor tools.
-from openerp.loglevels import get_encodings, ustr, exception_to_unicode
+from openerp.loglevels import get_encodings, ustr, exception_to_unicode # noqa
_logger = logging.getLogger(__name__)
"""
return izip(xrange(len(l)-1, -1, -1), reversed(l))
-#----------------------------------------------------------
-# SMS
-#----------------------------------------------------------
-# text must be latin-1 encoded
-def sms_send(user, password, api_id, text, to):
- import urllib
- url = "http://api.urlsms.com/SendSMS.aspx"
- #url = "http://196.7.150.220/http/sendmsg"
- params = urllib.urlencode({'UserID': user, 'Password': password, 'SenderID': api_id, 'MsgText': text, 'RecipientMobileNo':to})
- urllib.urlopen(url+"?"+params)
- # FIXME: Use the logger if there is an error
- return True
class UpdateableStr(local):
""" Class that stores an updateable string (used in wizards)
global __icons_list
return [(x, x) for x in __icons_list ]
-def extract_zip_file(zip_file, outdirectory):
- zf = zipfile.ZipFile(zip_file, 'r')
- out = outdirectory
- for path in zf.namelist():
- tgt = os.path.join(out, path)
- tgtdir = os.path.dirname(tgt)
- if not os.path.exists(tgtdir):
- os.makedirs(tgtdir)
-
- if not tgt.endswith(os.sep):
- fp = open(tgt, 'wb')
- fp.write(zf.read(path))
- fp.close()
- zf.close()
-
def detect_ip_addr():
"""Try a very crude method to figure out a valid external
IP or hostname for the current machine. Don't rely on this
'%Z': '',
}
+POSIX_TO_LDML = {
+ 'a': 'E',
+ 'A': 'EEEE',
+ 'b': 'MMM',
+ 'B': 'MMMM',
+ #'c': '',
+ 'd': 'dd',
+ 'H': 'HH',
+ 'I': 'hh',
+ 'j': 'DDD',
+ 'm': 'MM',
+ 'M': 'mm',
+ 'p': 'a',
+ 'S': 'ss',
+ 'U': 'w',
+ 'w': 'e',
+ 'W': 'w',
+ 'y': 'yy',
+ 'Y': 'yyyy',
+ # see comments above, and babel's format_datetime assumes an UTC timezone
+ # for naive datetime objects
+ #'z': 'Z',
+ #'Z': 'z',
+}
+
+def posix_to_ldml(fmt, locale):
+ """ Converts a posix/strftime pattern into an LDML date format pattern.
+
+ :param fmt: non-extended C89/C90 strftime pattern
+ :param locale: babel locale used for locale-specific conversions (e.g. %x and %X)
+ :return: unicode
+ """
+ buf = []
+ pc = False
+ quoted = []
+
+ for c in fmt:
+ # LDML date format patterns uses letters, so letters must be quoted
+ if not pc and c.isalpha():
+ quoted.append(c if c != "'" else "''")
+ continue
+ if quoted:
+ buf.append("'")
+ buf.append(''.join(quoted))
+ buf.append("'")
+ quoted = []
+
+ if pc:
+ if c == '%': # escaped percent
+ buf.append('%')
+ elif c == 'x': # date format, short seems to match
+ buf.append(locale.date_formats['short'].pattern)
+ elif c == 'X': # time format, seems to include seconds. short does not
+ buf.append(locale.time_formats['medium'].pattern)
+ else: # look up format char in static mapping
+ buf.append(POSIX_TO_LDML[c])
+ pc = False
+ elif c == '%':
+ pc = True
+ else:
+ buf.append(c)
+
+ # flush anything remaining in quoted buffer
+ if quoted:
+ buf.append("'")
+ buf.append(''.join(quoted))
+ buf.append("'")
+
+ return ''.join(buf)
+
def server_to_local_timestamp(src_tstamp_str, src_format, dst_format, dst_tz_name,
tz_offset=True, ignore_unparsable_time=True):
"""
def __enter__(self):
for logger in self.loggers:
+ assert isinstance(logger, basestring),\
+ "A logger name must be a string, got %s" % type(logger)
logging.getLogger(logger).addFilter(self)
def __exit__(self, exc_type=None, exc_val=None, exc_tb=None):
return [x for i, x in enumerate(args) if not strip(args, i)]
+
+class ConstantMapping(Mapping):
+ """
+ An immutable mapping returning the provided value for every single key.
+
+ Useful for default value to methods
+ """
+ __slots__ = ['_value']
+ def __init__(self, val):
+ self._value = val
+
+ def __len__(self):
+ """
+ defaultdict updates its length for each individually requested key, is
+ that really useful?
+ """
+ return 0
+
+ def __iter__(self):
+ """
+ same as len, defaultdict udpates its iterable keyset with each key
+ requested, is there a point for this?
+ """
+ return iter([])
+
+ def __getitem__(self, item):
+ return self._value
+
+
+def dumpstacks(sig, frame):
+ """ Signal handler: dump a stack trace for each existing thread."""
+ code = []
+
+ def extract_stack(stack):
+ for filename, lineno, name, line in traceback.extract_stack(stack):
+ yield 'File: "%s", line %d, in %s' % (filename, lineno, name)
+ if line:
+ yield " %s" % (line.strip(),)
+
+ # code from http://stackoverflow.com/questions/132058/getting-stack-trace-from-a-running-python-application#answer-2569696
+ # modified for python 2.5 compatibility
+ threads_info = dict([(th.ident, {'name': th.name, 'uid': getattr(th, 'uid', 'n/a')})
+ for th in threading.enumerate()])
+ for threadId, stack in sys._current_frames().items():
+ thread_info = threads_info.get(threadId)
+ code.append("\n# Thread: %s (id:%s) (uid:%s)" %
+ (thread_info and thread_info['name'] or 'n/a',
+ threadId,
+ thread_info and thread_info['uid'] or 'n/a'))
+ for line in extract_stack(stack):
+ code.append(line)
+
+ if openerp.evented:
+ # code from http://stackoverflow.com/questions/12510648/in-gevent-how-can-i-dump-stack-traces-of-all-running-greenlets
+ import gc
+ from greenlet import greenlet
+ for ob in gc.get_objects():
+ if not isinstance(ob, greenlet) or not ob:
+ continue
+ code.append("\n# Greenlet: %r" % (ob,))
+ for line in extract_stack(ob.gr_frame):
+ code.append(line)
+
+ _logger.info("\n".join(code))
+
+
+
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: