def deleteSalesForceObjects(sfdc, list_of_ids): import sys, traceback from vyperlogix import misc from vyperlogix.misc import ObjectTypeName deleted_ids = [] t_sfdc = ObjectTypeName.typeName(sfdc) if (t_sfdc.find('.connection.Connection') > -1): if (all([misc.isString(id) for id in list_of_ids])): try: delete_result = sfdc.delete(list_of_ids) deleted_ids = sfdc.resultToIdList(delete_result, success_status=True) except Exception as details: exc_info = sys.exc_info() info_string = '\n'.join(traceback.format_exception(*exc_info)) info_string = '%s :: Cannot process, Reason: %s\n%s' % ( misc.funcName(), str(details), info_string) print >> sys.stderr, info_string else: info_string = '%s :: Cannot process, Reason: "%s" is not a list of id(s) each being a string.' % ( misc.funcName(), str(list_of_ids)) print >> sys.stderr, info_string else: info_string = '%s :: Cannot process, Reason: "%s" is not a valid connection object to pyax however it appears to be "%s".' % ( misc.funcName(), str(sfdc), t_sfdc) print >> sys.stderr, info_string return deleted_ids
def __boolOp__(self, other, operation='&'): cname = ObjectTypeName.typeClassName(self).split('.')[-1] cls = eval(cname) if (isinstance(other, cls)): value = 0 if (operation == EnumInstance._boolOp_AND): value = self.value & other.value elif (operation == EnumInstance._boolOp_OR): value = self.value | other.value else: print_function( '(%s.%s) :: WARNING: Expected operation to be "%s" or "%s" but it is "%s".' % (ObjectTypeName.typeName(self), misc.funcName(), EnumInstance._boolOp_AND, EnumInstance._boolOp_OR, operation)) names = self.__names__(value) e = cls(self.parent, self.classname, EnumInstance._concat_symbol.join(names), value) return e else: print_function( '(%s.%s) :: ERROR: Expected other to be of type "%s" but it is of type "%s".' % (ObjectTypeName.typeName(self), misc.funcName(), ObjectTypeName.typeName(self), ObjectTypeName.typeName(other))) return None
def ProcessChange(self,action,fpath): fp = '/'.join([self.__watching__, fpath]).replace(os.sep,'/') if (callable(self.__callback__)): try: self.__callback__(self,action,fpath) except Exception as ex: self.queue_logging(logging.ERROR,'%s.1 :: %s' % (misc.funcName(),_utils.formattedException(details=ex))) self.queue_logging(logging.INFO,'%s.1 :: (%s) (%s) %s' % (misc.funcName(), action.name, 'D' if (os.path.isdir(fp)) else 'F' if (os.path.isfile(fp)) else 'U', fp))
def data_hook(data_path): global _metadata logging.info('%s.1 :: %s' % (misc.funcName(), data_path)) if (os.path.exists(data_path)): logging.info('%s.2 :: %s' % (misc.funcName(), data_path)) _metadata['_data_path'] = None _metadata['_data_path'] = data_path if ( sys.platform[:3] != 'win') else data_path.replace('/', os.sep) return data_path
def openPickledHashBasedOnFilename(filename, method=PickleMethods.none): '''Uses the filename to determine which class should be used to open the database file. Fails with a list if filename has more than one variation present in the same folder.''' def deMungeFileName(fname): if (isFilenameMungedAlready(fname)): toks = fname.split('_') if (len(toks) > 2): while (len(toks) > 2): toks[0] = '_'.join(toks[0:2]) del toks[1] _toks = toks[-1].split('.') _fname = '.'.join([toks[:len(toks) - 1][0], _toks[-1]]) _tag = '_' + _toks[0] return (fname, _fname, _tag) return (None, None) dname = os.path.dirname(filename) if (len(dname) == 0): dname = os.path.abspath('.') _obj = None _tag = '' fname = os.path.basename(filename) fname, _fname, _tag = deMungeFileName(fname) toks = fname.split('.') if (len(toks) > 1): toks[-1] = '.' + toks[-1] files = [deMungeFileName(f) for f in os.listdir(dname)] files = [f[1] for f in files if (f[0] == fname) and (f[-1] == _tag)] if (len(files) == 1): if (len(_tag) == 0): return openPickledHashBasedOnFilename(os.sep.join( [dname, files[0]]), method=method) i = misc.findInListSafely(__classes_tags, _tag) if (i > -1): info_string = '' toks = ObjectTypeName._typeName(__classes[i]).split('.') className = toks[len(toks) - 1:][0] try: s = '%s(filename,method=method)' % (className) _obj = eval(s) except TypeError: try: s = '%s(filename)' % (className) _obj = eval(s) except Exception as details: info_string = str(details) else: raise ValueError( '(%s) :: Cannot figure-out the class name based on "%s", recommend working this out on you own because you seemed to have written some bad code or maybe "%s".' % (misc.funcName(), _tag, info_string)) else: raise ValueError( '(%s) :: Too %s files (%d) named like "%s" %s for %s, recommend using the class name "%s" and open it yourself.' % (misc.funcName(), 'many' if (len(files) > 1) else 'few', len(files), str(files), str(toks), filename, _tag)) return _obj
def __callback__(*args, **kwargs): print 'DEBUG.%s: args=%s, kwargs=%s' % (misc.funcName(),args,kwargs) new_dirname = args if (__dest__): if (not os.path.exists(__dest__)): os.makedirs(__dest__) if (len(args) > 0): new_dirname = args[0].replace(os.path.dirname(args[0]),__dest__) elif (__opath__): if (not os.path.exists(__opath__)): os.makedirs(__opath__) if (len(args) > 0): new_dirname = args[0].replace(args[0],__opath__) print 'DEBUG.%s: new_dirname=%s' % (misc.funcName(),new_dirname) return new_dirname
def fromDict(self, args): if (lists.isDict(args)): try: __iter__ = args.iteritems() except: try: __iter__ = args.asPythonDict().iteritems() except: try: __iter__ = args.asDict().iteritems() except: __iter__ = None for ak, av in __iter__: try: for k, v in av.iteritems(): self.__dict__['%s_%s' % (ak, k)] = v except: self.__dict__[ak] = av if (not misc.isList(av)) else [ item if (not lists.isDict(item)) else self.__class__(item) for item in av ] else: logging.warning( '(%s.%s) :: Illegal args variable, expected type "dict" but got type "%s".' % (ObjectTypeName.typeName(self), misc.funcName(), ObjectTypeName.typeName(args)))
def tcpipConnector(_cmd): value = '{}' try: if (len(_cmd) > 0): if (logger): logger.debug('DEBUG.%s.1: _cmd=%s' % (misc.funcName(),_cmd)) __data__ = simplejson.loads(_cmd) if (logger): logger.debug('DEBUG.%s.2: __data__=%s' % (misc.funcName(),__data__)) try: return __processConnection__(__data__) except Exception, details: value = simplejson.dumps({'exception':details}) except Exception, details: value = simplejson.dumps({'exception':details})
def rewrite_anchor(_url, params='', callback=None, isDebug=False): from vyperlogix import misc from vyperlogix.misc import _utils _url = _url.lower() subject = _url if (_url.find('.php') > -1): toks2 = _url.split('"') toks2_3 = (len(toks2) == 3) if (len(toks2) == 1) or (toks2_3): toks3 = toks2[1 if (toks2_3) else 0].split('?') if (len(toks3) == 2): try: toks4 = [ tuple(t.split('=')) for t in toks3[-1].replace('&&', '&').split('&') ] d_toks4 = dict([t for t in toks4 if (len(t) == 2)]) if (len(params) > 0): d_toks4[ 'params'] = _utils.parse_key_value_pairs_as_dict( params) if (misc.isString(params)) else '' if (callable(callback)): try: if (isDebug): print '%s :: %s' % (misc.funcName(), str(d_toks4)) href = callback(d_toks4) except: href = _url # do nothing if there is not a callback... return href except Exception as details: print >> sys.stderr, _utils.formattedException( details=details) return _url
def runWithAnalysis(func=dummy,args=[],_ioElapsedTime=dummy,num_iters=None): caller = misc.callersName() ioTimeAnalysis.initIOTime('%s::%s' % (__name__,caller)) ioTimeAnalysis.ioBeginTime('%s::%s' % (__name__,caller)) val = None try: if (len(args) == 0): val = func() else: val = func(args) except: exc_info = sys.exc_info() info_string = '\n'.join(traceback.format_exception(*exc_info)) print >>sys.stderr, '(%s) Reason: %s' % (misc.funcName(),info_string) ioTimeAnalysis.ioEndTime('%s::%s' % (__name__,caller)) ioTimeAnalysis.ioTimeAnalysisReport() _et = 0 _key_list = [k for k in ioTimeAnalysis._ioTime.keys()] for _key in _key_list: _et += (0 if (len(_key) == 0) else ioTimeAnalysis._ioTime[_key][0]) if (_et > 0) and (num_iters is not None): _per_sec = num_iters / _et if (_per_sec > 0): _ms_per_soql = 1000 / _per_sec else: print >>sys.stderr, '(%s) 1.0 Cannot correctly report ms per iteration because there is no reported elapsed time from activities.' % (misc.funcName()) return val
def typeName(obj): from vyperlogix import misc callersName = misc.callersName() if (any([(callersName.find(n) > -1) for n in ['__str__', '__repr__']])): raise UserWarning( '(%s) :: Cannot call this function from a __str__ function - recode this yourself using the helper function.' % (misc.funcName())) return __typeName(obj).replace("'", '').replace('>', '')
def killProcByPID(pid,isVerbose=False): info_string = '' if (isVerbose): print >>sys.stderr, '(%s) :: sys.platform is "%s".' % (misc.funcName(),sys.platform) if (sys.platform == 'win32'): def kill(pid): info_string = '' from vyperlogix.win import WinProcesses p = WinProcesses.WinProcesses() proc_handle = p.openProcessTerminateForPID(pid) if (isVerbose): print >>sys.stderr, '(%s) :: proc_handle is "%s".' % (misc.funcName(),proc_handle) if (proc_handle): try: import win32api win32api.TerminateProcess(proc_handle, -1) except Exception as details: from vyperlogix.misc import _utils info_string += _utils.formattedException(details=details) try: import ctypes ctypes.windll.kernel32.TerminateProcess(proc_handle, -1) except Exception as details: from vyperlogix.misc import _utils info_string += _utils.formattedException(details=details) print >>sys.stderr, 'ERROR: Cannot Kill the process with pid of %s due to a system error.' % (pid) print >>sys.stderr, info_string finally: p.closeProcessHandle(proc_handle) if (isVerbose): print >>sys.stderr, '(%s) :: kill(%d).' % (misc.funcName(),pid) kill(pid) else: try: os.kill(pid) except Exception as details: from vyperlogix.misc import _utils info_string += _utils.formattedException(details=details) print >>sys.stderr, 'ERROR: Cannot kill the process !' print >>sys.stderr, info_string if (isVerbose): print >>sys.stderr, '(%s) :: info_string is "%s".' % (misc.funcName(),info_string)
def all(args, use_logging=False): r = [[]] if (misc.isList(args)): _args = [i if (misc.isList(i)) else [i] for i in args] for x in args: r = [i + [y] for y in x for i in r] else: if (use_logging): logging.warning('%s.1 :: Cannot figure-out what to do with %s.' % (misc.funcName(), args)) return r
def __new__(cls, parent, classname, enumname, value): self = super(EnumInstance, cls).__new__(cls, str(value)) self.__parent = parent self.__classname = classname if (misc.isString(enumname)): self.__enumname = enumname self.__value = value elif (misc.isList(enumname)): self.__value = 0 for n in enumname: val = parent[n].value self.__value |= val assert self.__value == value, '(%s.%s) :: ERROR: Why the freak is the value of "%s" not equal to "%s"; the value that was stated to equate to "%s" cannot be correct according to the actual values from the parent of this %s object.' % ( ObjectTypeName.typeName(self), misc.funcName(), self.__value, value, enumname, ObjectTypeName.typeName(self)) else: print_function( '(%s.%s) :: ERROR: What the freak is the meaning of enumname of "%s" of type "%s".' % (ObjectTypeName.typeName(self), misc.funcName(), enumname, ObjectTypeName.typeName(enumname))) return self
def prune(self, pattern, _max): logging.info('Prune Log for "%s".' % (self.logFileName)) files = misc.sort(glob.glob(pattern)) numToDelete = len(files) - _max if (numToDelete > 0): for f in files[0:numToDelete]: try: os.remove(f) logging.info('(%s) :: Removed "%s".' % (misc.funcName(), f)) except Exception as details: info_string = _utils.formattedException(details=details) logging.warning(info_string)
def __shell__(self,cmd,isExit=True,isWait=False,isVerbose=True): if (callable(self.__callback__)): try: self.__callback__(None) except Exception as ex: info_string = _utils.formattedException(details=ex) print >> sys.stderr, info_string _isExit=isExit _isWait=isWait if (self.__isDebugging__): print '%s.1 --> cmd=%s, isExit=%s, isWait=%s, isVerbose=%s' % (misc.funcName(),cmd,_isExit,_isWait,isVerbose) s = Popen.Shell(cmd, shell=None, env=None, isExit=_isExit, isWait=_isWait, isVerbose=isVerbose, fOut=self.__callback__, onExit=self.__onExit__) return
def __callback2__(*args, **kwargs): __re1__ = re.compile("@@@delete=(?P<filename>.*)@@@", re.DOTALL | re.MULTILINE) data = args[0] if (misc.isIterable(args) and (len(args) > 0)) else args matches1 = __re1__.search(data) if (matches1): f = matches1.groupdict().get('filename',None) if (f): fpath = os.sep.join([__ipath__,f]) if (os.path.exists(fpath) and os.path.isfile(fpath)): print 'INFO: Removing "%s".' % (fpath) os.remove(fpath) print 'DEBUG.%s: args=%s, kwargs=%s' % (misc.funcName(),args,kwargs) return None
def login(self): if (self.smtp_port < 1): toks = self.smtp_server.split(':') self.smtp_server = toks[0] self.smtp_port = -1 if (len(toks) != 2) else -1 if ( not toks[-1].isdigit()) else int(toks[-1]) if (len(self.smtp_server) > 0) and (isinstance( self.smtp_port, int)) and (self.smtp_port > -1): print '(%s.%s) :: smtpServer=[%s], port=[%s], username=[%s], password=[%s]' % ( ObjectTypeName.typeName(self), misc.funcName(), self.smtp_server, self.smtp_port, self.smtp_username, self.smtp_password) try: self.mailServer = smtplib.SMTP(host=self.smtp_server, port=self.smtp_port) self.mailServer.set_debuglevel(self.debug) if (len(self.smtp_username) > 0) and (len(self.smtp_password) > 0): self.mailServer.login(self.smtp_username, self.smtp_password) except Exception as details: tbinfofile = StringIO.StringIO() traceback.print_exc(None, tbinfofile) tbinfofile.seek(0) tbinfo = tbinfofile.read() _msg = '(%s.%s) :: ERROR due to "%s"\n%s.' % ( ObjectTypeName.typeName(self), misc.funcName(), details, tbinfo) print >> sys.stderr, _msg raise smtplib.SMTPConnectError(_msg) self.log = self.logger else: _msg = '(%s.%s) :: WARNING :: Invalid SMTP Configuration that does not work, recommend checking your choices and attributes because something is wrong. smtpServer=[%s], port=[%s], username=[%s], password=[%s]' % ( ObjectTypeName.typeName(self), misc.funcName(), self.smtp_server, self.smtp_port, self.smtp_username, self.smtp_password) print >> sys.stderr, _msg raise ValueError(_msg)
def __shell__(self, cmd, isExit=False, isWait=True, isVerbose=True): misc.removeAll(self.__lines__) _isExit = isExit _isWait = isWait if (self.__isDebugging__): print '%s.1 --> cmd=%s, isExit=%s, isWait=%s, isVerbose=%s' % ( misc.funcName(), cmd, _isExit, _isWait, isVerbose) s = Popen.Shell(cmd, shell=None, env=None, isExit=_isExit, isWait=_isWait, isVerbose=isVerbose, fOut=self.__callback__) return
def get_ip_address(ifname): try: import fcntl s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) return socket.inet_ntoa( fcntl.ioctl( s.fileno(), 0x8915, # SIOCGIFADDR struct.pack('256s', ifname[:15]))[20:24]) except: import platform from vyperlogix import misc print >> sys.stderr, '%s.WARNING: Cannot use this function in %s.' % ( misc.funcName(), platform.uname()[0]) return None
def fromDict(self, args): if (lists.isDict(args)): for ak, av in args.iteritems(): if (lists.isDict(av)): self.__dict__[ak] = SmartObject(av) else: self.__dict__[ak] = av if (not misc.isList(av)) else [ item if (not lists.isDict(item)) else self.__class__(item) for item in av ] else: logging.warning( '(%s.%s) :: Illegal args variable, expected type "dict" but got type "%s".' % (ObjectTypeName.typeName(self), misc.funcName(), ObjectTypeName.typeName(args)))
def getDaemons(prefix, fpath): import re from vyperlogix import misc _name = misc.funcName() s_regex = r".+%s\.((py)|(pyc)|(pyo))" % ('_tasklet') s_svn_regex = '[._]svn' _regex = re.compile(s_regex) svn_regex = re.compile(s_svn_regex) files = [f for f in os.listdir(os.path.abspath(fpath)) if _regex.search(f)] rejects = [ f for f in os.listdir(os.path.abspath(fpath)) if (not _regex.search(f)) and (not svn_regex.search(f)) and ( f.find('__init__.') == -1) and (f.find('dlib') == -1) ] if (len(rejects) > 0): print >> sys.stderr, '(%s) :: Rejected daemon files are "%s" using (not "%s") and (not "%s"). PLS check the file names to ensure your daemons will be executed as planned.' % ( _name, rejects, s_regex, s_svn_regex) return files
def weave_into(target, phrase): from vyperlogix.iterators import iterutils normalize = lambda foo, m: foo + ('00' * (m - (len(foo) / 2)) if ((len(foo) / 2) < m) else '') results = [] target = _utils.ascii_only(target) phrase = _utils.ascii_only(phrase) m = max(len(target) / 2, len(phrase) / 2) m += m % 2 target = normalize(target, m) phrase = normalize(phrase, m) assert len(target) == len( phrase), 'ERROR: Something went wrong with the normalization in %s' % ( misc.funcName()) pGen = (pCh for pCh in iterutils.itergroup([p for p in phrase], 2)) for t in iterutils.itergroup([i for i in target], 2): results.append(''.join(t)) results.append(''.join(pGen.next())) return ''.join(results)
def typeClassName(obj): from vyperlogix import misc callersName = misc.callersName() if (any([(callersName.find(n) > -1) for n in ['__str__', '__repr__']])): raise UserWarning( '(%s) :: Cannot call this function from a __str__ function - recode this yourself using the helper function.' % (misc.funcName())) try: sObj = str(obj.__class__) except AttributeError: sObj = str(obj) except: return typeName(obj) toks = sObj.replace('<', '').replace('>', '').replace("'", '').replace( 'object at', 'object_at').split() i = misc.findInListSafely(toks, 'object_at') if (i > 0): i -= 1 else: return toks[-1] return toks[0]
def __private__(self, entry, *args, **kwargs): from vyperlogix.misc import _utils def method1(args, kw): print 'method1 args=%s, kw=%s' % (args, kw) try: ctx = _utils.callersContext() if (ctx.co_name in dir(self)): x = eval('%s(args,kwargs)' % entry) return x except: from vyperlogix import misc exc_info = sys.exc_info() info_string = '\n'.join(traceback.format_exception(*exc_info)) logging.warning( '(%s) :: Cannot call private method named "%s"...%s' % (misc.funcName(), entry, info_string)) raise ReferenceError( 'Cannot issue a call to a private method (%s) from outside the context of the class where this method is defined.' % (entry))
def getPDFContent(path,delimiter=' '): import pyPdf from vyperlogix.hash import lists from vyperlogix.misc.decodeUnicode import decodeUnicode d_content = lists.HashedLists2() fIn = file(path, "rb") try: pdf = pyPdf.PdfFileReader(fIn) for i in xrange(0, pdf.getNumPages()): d_content[i+1] = " ".join(pdf.getPage(i).extractText().replace("\xa0", " ").strip().split()) except: import sys import traceback from vyperlogix import misc exc_info = sys.exc_info() info_string = '\n'.join(traceback.format_exception(*exc_info)) print >>sys.stderr, '(%s) Error due to "%s".' % (misc.funcName(),info_string) finally: fIn.close() return d_content
def ssh_connect_transport(self): """ Make an SSH connection with the server to mimic certain functions only for win32 platform to facilitate development. """ # get host key, if we know one hostkeytype = None hostkey = None try: host_keys = paramiko.util.load_host_keys( os.path.expanduser('~/.ssh/known_hosts')) except IOError: try: host_keys = paramiko.util.load_host_keys( os.path.expanduser('~/ssh/known_hosts')) except IOError: exc_info = sys.exc_info() info_string = '\n'.join(traceback.format_exception(*exc_info)) print >> self.lastError, '\n%s :: Cannot open host keys file, Reason: %s' % ( ObjectTypeName.objectSignature(self), info_string) host_keys = {} if host_keys.has_key(self.hostname): hostkeytype = host_keys[self.hostname].keys()[0] hostkey = host_keys[self.hostname][hostkeytype] else: print "%s :: Host key not found. Please create key manually using: ssh %s" % ( misc.funcName(), self.hostname) # now, connect and use paramiko Transport to negotiate SSH2 across the connection try: t = paramiko.Transport((self.hostname, self.port)) t.connect(username=self.username, password=self.password, hostkey=hostkey) except Exception as e: exc_info = sys.exc_info() info_string = '\n'.join(traceback.format_exception(*exc_info)) print >> self.lastError, '\n%s :: Cannot open connection to %s:%s using username of "%s", Reason: %s' % ( ObjectTypeName.objectSignature(self), self.hostname, self.port, self.username, info_string) return None return t
def redirectStdErrOutWrapper(func=dummy, args=[], top=os.path.abspath('.')): info_string = '' if (callable(func)): _stderr = sys.stderr _stdout = sys.stdout fStderr = open(os.sep.join([top, 'stderr.txt']), 'w') fStdout = open(os.sep.join([top, 'stdout.txt']), 'w') sys.stdout = daemon.Log(fStdout) sys.stderr = daemon.Log(fStderr) try: ret = func(args) except: exc_info = sys.exc_info() info_string = '\n'.join(traceback.format_exception(*exc_info)) finally: sys.stderr.close() sys.stderr = _stderr sys.stdout.close() sys.stdout = _stdout print >> sys.stderr, info_string else: print >> sys.stderr, '%s :: Cannot process this function due to an error in the parameters, are you sure you are awake ?' % ( misc.funcName()) return ret
def record_results(self,results): if (results != None): _name = misc.funcName() _dbx = self.dbx ts = _utils.timeStamp() nk1 = len(_dbx.keys()) _keys = _dbx.normalizedSortedKeys() if (len(_keys) > 0): try: _last_i = int(_keys[0].split(',')[0]) except: _last_i = -1 else: _last_i = 0 if (_last_i > -1): _dbx['%d,%s' % (_last_i+1,ts)] = results nk2 = len(_dbx.keys()) logging.info('(%s) :: There were %d key%s but now %d key%s in the file named %s.' % (_name,nk1,'s' if nk1 > 1 else '',nk2,'s' if nk2 > 1 else '',self.c_dbxName)) for k in _keys[0:5]: logging.info('(%s) :: %s.' % (_name,k)) _dbx.sync() _dbx.close() else: logging.warning('Unable to record the results due to there are no results to record because results are of type "%s".' % (type(results)))
def current_site(): from django.conf import settings from vyperlogix import misc _current_site = settings.CURRENT_SITE logging.debug('%s.1 --> _current_site=%s' % (misc.funcName(),_current_site)) return _current_site
def process_message(self, peer, mailfrom, rcpttos, data): f_unpack = lambda foo, key: foo[key][0] if (misc.isList(foo[key]) ) else foo[key] try: SmtpMailsinkServer._count_messages += 1 try: d = self.parseMessage(data) except: exc_info = sys.exc_info() info_string = '\n'.join(traceback.format_exception(*exc_info)) logMessage(info_string, ObjectTypeName.typeName(self), misc.funcName(), _logging=standardLogging.LoggingLevels.error) if (self.multi_file): _toAddr = f_unpack(d, const_to_symbol) _path = _utils.safely_mkdir(fpath=self.cwd, dirname=os.sep.join( ['mailboxes', _toAddr])) _fMbx = self.mailboxFile self.mailboxFile = open( '%s.%s' % (os.sep.join([ _path, _utils.timeStamp().replace(':', '') ]), 'html' if (self.use_html) else 'txt'), 'w') info_string = 'DEBUG: self.mailboxFile is "%s".' % ( self.mailboxFile) logMessage(info_string, ObjectTypeName.typeName(self), misc.funcName(), _logging=standardLogging.LoggingLevels.error) if self.mailboxFile is not None: #_utils.print_stderrout("Mail From is %s\n" % mailfrom) try: io_buffer = _utils.stringIO() if (self.is_debugging): d.prettyPrint(prefix='', title='Mail Parts', fOut=io_buffer) else: if (self.use_html): print >> io_buffer, self.renderHTML( f_unpack(d, const_subject_symbol), f_unpack(d, const_body_symbol)) else: print >> io_buffer, '%s' % (f_unpack( d, const_subject_symbol)) print >> io_buffer, '%s' % ('\n'.join( f_unpack(d, const_body_symbol))) s = io_buffer.getvalue() self.mailboxFile.write(s) except: exc_info = sys.exc_info() info_string = '\n'.join( traceback.format_exception(*exc_info)) logMessage(info_string, ObjectTypeName.typeName(self), misc.funcName(), _logging=standardLogging.LoggingLevels.error) #self.mailboxFile.write( "="*80 ) #self.mailboxFile.write( "\n\n" ) self.mailboxFile.flush() if (self.multi_file): self.mailboxFile.close() self.mailboxFile = _fMbx else: print >> sys.stderr, 'ERROR: self.mailboxFile is "%s".' % ( self.mailboxFile) if (callable(self.callback)): try: info_string = 'DEBUG: mailfrom is "%s", rcpttos is "%s".' % ( mailfrom, rcpttos) logMessage(info_string, ObjectTypeName.typeName(self), misc.funcName(), _logging=standardLogging.LoggingLevels.error) self.callback(d, mailfrom, rcpttos, data) except: exc_info = sys.exc_info() info_string = '\n'.join( traceback.format_exception(*exc_info)) logMessage(info_string, ObjectTypeName.typeName(self), misc.funcName(), _logging=standardLogging.LoggingLevels.error) else: logMessage( 'Cannot issue callback because callback is not callable.', ObjectTypeName.typeName(self), misc.funcName(), _logging=standardLogging.LoggingLevels.warning) info_string = 'SmtpMailsinkServer._count_messages=%d' % ( SmtpMailsinkServer._count_messages) logMessage(info_string, ObjectTypeName.typeName(self), misc.funcName(), _logging=standardLogging.LoggingLevels.info) except: exc_info = sys.exc_info() info_string = '\n'.join(traceback.format_exception(*exc_info)) logMessage(info_string, ObjectTypeName.typeName(self), misc.funcName(), _logging=standardLogging.LoggingLevels.error)
def renderHTML(self, subj, body): from vyperlogix.html import myOOHTML as oohtml h_html = oohtml.Html() def renderBody(_body): h = oohtml.Html() h_html = h.tag(oohtml.oohtml.HTML) h_body = h_html.tag(oohtml.oohtml.BODY) h_Content = h_body.tag(oohtml.oohtml.DIV, id="content", style="background-color: white") _body = _body[0] if (misc.isList(_body)) and (len(_body) == 1) else _body h_Content.text(_body[0]) if (len(_body) > 1): for b in _body[1:]: h_Content.tagOp(oohtml.oohtml.BR) h_Content.text(b) return h_Content.toHtml() if (not misc.isString(subj)): subj = str(subj) if (not misc.isList(body)): body = [body] if (misc.isString(subj)) and (misc.isList(body)): h_html.text(oohtml.oohtml.DOCTYPE_40_TRANSITIONAL) _title = "Vyper Logix SMTP Email Proxy (%s v.%s)" % ( ObjectTypeName.typeName(self), __version__) html_html = h_html.tag(oohtml.oohtml.HTML) head_html = html_html.tag(oohtml.oohtml.HEAD) head_html.tagOp(oohtml.oohtml.META, http_equiv=oohtml.oohtml.CONTENT_TYPE, content=oohtml.oohtml.TEXT_HTML_CHARSET_ISO_8859_1) head_html.metas(( oohtml.oohtml.AUTHOR, '%s :: %s' % (self.author, self.__author__) ), (oohtml.oohtml.KEYWORDS, _title), ( oohtml.oohtml.DESCRIPTION, "The contents of this email are considered to be confidential unless otherwise specified." ), (oohtml.oohtml.ROBOTS, oohtml.oohtml.ALL)) head_html.tagTITLE( '©%s, Vyper Logix Corp., All Rights Reserved., %s' % (_utils.timeStamp(format=_utils.formatDate_YYYY()), _title)) body_html = html_html.tag(oohtml.oohtml.BODY) idContent = body_html.tag(oohtml.oohtml.DIV, id="content", style="background-color: white") rows = [] rows.append(tuple(['%s' % (subj)])) rows.append(tuple([renderBody(body)])) rows.append(tuple(['<BR/><BR/><BR/><BR/>'])) rows.append( tuple([ self.copyright if (misc.isString(self.copyright)) and (len(self.copyright) > 0) else self.__copyright__ ])) idContent.html_table(rows) pass else: logMessage( 'subj must be of type str and body must be of type list rather than of types "%s" and "%s", respectively.' % (type(subj), type(body)), ObjectTypeName.typeName(self), misc.funcName(), _logging=standardLogging.LoggingLevels.warning) return h_html.toHtml()
def __callback__(*args, **kwargs): print 'DEBUG.%s: args=%s, kwargs=%s' % (misc.funcName(),args,kwargs) return args[0].replace('@vm2','@vm1') if (len(args) > 0) else args
def get_ip_address(ifname): try: import fcntl s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) return socket.inet_ntoa( fcntl.ioctl( s.fileno(), 0x8915, # SIOCGIFADDR struct.pack('256s', ifname[:15]))[20:24]) except: import platform from vyperlogix import misc print >> sys.stderr, '%s.WARNING: Cannot use this function in %s.' % ( misc.funcName(), platform.uname()[0]) return None def get_ip_address_by_socket(): return socket.gethostbyname(socket.gethostname()) if (__name__ == '__main__'): import platform from vyperlogix.misc import _utils if (_utils.isUsingWindows): print >> sys.stderr, '%s.WARNING: Cannot use this function in %s.' % ( misc.funcName(), platform.uname()[0]) else: print get_ip_address('eth0')
def prettyPrint(item, prefix='', title='', tab_width=4, delay_end=False, asCSV=False, isHorizontal=False, csv_callback=None, fOut=sys.stdout): import types from vyperlogix.misc import ReportTheList _type_name = ObjectTypeName._typeName(item.__class__) ret = [] try: if (isDict(item)): tab_width = 4 if (not str(tab_width).isdigit()) else tab_width if (asCSV): if (isHorizontal): fOut.write('%s\n' % (misc.asCSV(item.keys()))) fOut.write('%s\n' % (misc.asCSV(item.values()))) fOut.write('\n') else: isCallback = ((csv_callback) and (callable(csv_callback))) i = 1 for kk, vv in item.iteritems(): l = [i, kk, vv] if (isCallback): try: l = csv_callback(l) except: pass fOut.write('%s\n' % (misc.asCSV(l))) i += 1 else: l_keys = [len(kk) for kk, vv in item.iteritems()] if (len(l_keys) > 0): max_len = misc.sort(l_keys)[-1] fOut.write('%sBEGIN: %s (%d items)\n' % (prefix, title, len(item))) i = 1 for kk, vv in item.iteritems(): i_s_len = int(len(kk) / tab_width) i_s_len = 1 if (i_s_len == 0) else i_s_len i_spaces = (int(max_len / tab_width) - i_s_len) - 1 if (isinstance(vv, tuple)): vv = list(vv) if (isinstance(vv, list)): fOut.write('(%s' % ('-' * 40)) ReportTheList.reportTheList(vv, title='%d :: (%s) %s' % (i, kk, title), fOut=fOut) fOut.write(')%s' % ('-' * 40)) fOut.write('\n') elif (isDict(vv)): fOut.write('{%s' % ('-' * 40)) prettyPrint(vv, '\t\t', title='%d :: (%s) %s' % (i, kk, title), fOut=fOut) fOut.write('}%s' % ('-' * 40)) fOut.write('\n') else: try: fOut.write( '%s\t\t%d :: %s%s-->%s' % (prefix, i, kk, '\t' * i_spaces, vv)) except: pass i += 1 _end_msg = '%sEND! %s from %s' % (prefix, title, _type_name) if (not delay_end): fOut.write(_end_msg) fOut.write('\n') else: ret.append(_end_msg) ret.append('') else: logging.warning( '(%s) :: Unable to process the object passed to this function due to lack of data.' % (misc.funcName())) else: logging.warning( '(%s) :: Unable to process the object passed to this function because it is of type "%s" and a dictionary object was expected.' % (misc.funcName(), _type_name)) except Exception as details: info_string = misc.formattedException(details=details) sys.stderr.write(info_string) return ret