def ProcessFile(fpath,output=None): import socket global __writer__ if (fpath and os.path.exists(fpath) and (os.path.isfile(fpath))): if (__writer__): while (1): try: __writer__.sendFile(fpath,__eof__=__eof__) # To do: Ensure the file was received and stored at the other end however for now we simply assume that happened because no exceptions. #os.remove(fpath) break except socket.error: print 'INFO: Restarting Socket Writer on %s:%s.' % (__writer__.ipAddress, __writer__.portNum) __writer__ = tcpipbridge.SocketWriter(__writer__.ipAddress, __writer__.portNum,retry=__writer__.retry) if (__is_listener__): __writer__.send('@@@address=%s:%s@@@' % (listen_to_ip,listen_to_port)) except Exception, ex: print >> sys.stderr, 'EXCEPTION: %s' % (_utils.formattedException(details=ex)) else: if (output and os.path.exists(output) and os.path.isdir(output)): try: dest = os.sep.join([output,os.path.basename(fpath)]) _utils.copyFile(fpath, dest, no_shell=True) print >> sys.stdout, 'DEBUG: PROCESS --> %s --> %s' % (fpath,dest) if (os.path.exists(dest)): os.remove(fpath) except Exception, ex: print >> sys.stderr, 'EXCEPTION: %s' % (_utils.formattedException(details=ex))
def doExit(self): try: send_all(self.proc, 'exit' + self.tail) if (self.isVerbose): if (callable(self.fOut)): try: data = recv_some(self.proc) except: data = None if (data is not None) and (len(data) > 0): try: self.fOut(data) except Exception as details: info_string = _utils.formattedException(details=details) print >> _target_[0:2], info_string else: try: data = recv_some(self.proc, e=0) except: data = None if (data is not None) and (len(data) > 0): print >>self.fOut, data except: pass # suppress because the other side may have become disconnected simply because we have all the content from it... if (callable(self.__onExit__)): try: self.__onExit__() except Exception as details: info_string = _utils.formattedException(details=details) print >> sys.stderr, info_string
def unZipInto(_zip,target,isVerbose=False,callback=None): try: iterable = None typ = ObjectTypeName.typeClassName(_zip) if (typ == 'zipfile.ZipFile'): iterable = (f.filename for f in _zip.filelist) else: raise AttributeError('Invalid _zip attribute cann be of type "%s".' % (typ)) if (isVerbose): print '*** iterable = %s' % (str(iterable)) if (iterable): for f in iterable: _f_ = __normalize__(f) fname = os.path.join(target,_f_) if (f.endswith('/')): if (not os.path.exists(fname)): os.makedirs(fname) if (callable(callback)): try: callback(EntityType.folder,f) except: pass else: __bytes__ = _zip.read(f) if (isVerbose): print '%s -> %s [%s]' % (f,fname,__bytes__) _utils.writeFileFrom(fname,__bytes__,mode='wb') if (callable(callback)): try: callback(EntityType.file,f,fname) except: pass except Exception, _details: if (isVerbose): print _utils.formattedException(details=_details)
def parse(self): try: from vyperlogix.xlrd import excelReader decode_and_strip = lambda aString:self.decode_and_strip(aString) self.__header__ = None self.__rows_dicts__ = [] self.__reader__ = reader = excelReader.readexcel(self.filename) self.__sheets__ = sheets = reader.worksheets() for sheet in sheets: for row in reader.getiter(sheet): if (self.__header__ is None): self.__header__ = [decode_and_strip(h) for h in row if (len(decode_and_strip(h)) > 0)] self.__num_headers__ = len(self.header) else: header = self.header _row = {} for k,v in row.iteritems(): if (v is None): row[k] = '' try: _k = decode_and_strip(k) except UnicodeEncodeError, details: info_string = _utils.formattedException(details=details) print >>sys.stderr, info_string try: _v = decode_and_strip(v) except UnicodeEncodeError, details: info_string = _utils.formattedException(details=details) print >>sys.stderr, info_string _row[_k] = _v d = self.dict2_factory(_row) self.__rows_dicts__.append(d)
def __init__(self, args): self.__named_argument_or_else = lambda name, default: self.arguments[ name] if self.arguments.has_key(name) else default self.__normalize_option_name = lambda name: name.split('--')[-1] self.__normalize_boolean_name = lambda name: 'is' + self.__normalize_option_name( str(name)).capitalize() self.__named_boolean_or_else = lambda name, default: self.booleans[ self.__normalize_boolean_name(name)] if self.booleans.has_key( self.__normalize_boolean_name(name)) else default self.__make_key__ = lambda key: '_' + str(key) super(SmartArgs, self).__init__(args, as_list=True) self.progName = self.programName self.progID = os.path.splitext(self.programName)[0] for k, v in args.iteritems(): toks = k.split('=') if (len(toks) > 1): toks[0] = toks[0].split('--')[-1] self[toks[0]] = '' try: self[toks[0]] = self.__named_argument_or_else( toks[0], self[toks[0]]) except Exception as e: info_string = _utils.formattedException(details=e) print >> sys.stderr, info_string else: _k_ = self.__normalize_boolean_name(k) self[_k_] = False try: self[_k_] = self.__named_boolean_or_else(k, self[_k_]) except Exception as e: info_string = _utils.formattedException(details=e) print >> sys.stderr, info_string self[_k_] = False pass
def updated_as_timestamp(updated): import re from vyperlogix.lists.ListWrapper import ListWrapper try: _reOtherDate = re.compile(r"(19|20)[0-9]{2}[- /.](0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])T((([0]?[1-9]|1[0-2])(:|\.)[0-5][0-9]((:|\.)[0-5][0-9])?( )?(AM|am|aM|Am|PM|pm|pM|Pm))|(([0]?[0-9]|1[0-9]|2[0-3])(:|\.)[0-5][0-9]((:|\.)[0-5][0-9])?))\+(([0]?[0-9]|1[0-9]|2[0-3])(:|\.)[0-5][0-9]((:|\.)[0-5][0-9])?)") if (not isinstance(updated,datetime.datetime)): matches = _reOtherDate.search(updated) try: return _utils.getFromDateStr(updated.split('+')[0].strip(),format=_utils.formatMetaHeaderExpiresOn()) if (not matches) else _utils.getFromDateStr(updated.split('+')[0],format=_utils._formatTimeStr()) except: return _utils.getFromDateStr(updated,format=_utils.formatMetaHeaderExpiresOnZ()) except Exception, e: #info_string = _utils.formattedException(details=e) try: return _utils.getFromDateStr(updated.split('+')[0].strip(),format=_utils._formatTimeStr()) except: fmt = make_sense_of_time_string(updated) try: return _utils.getFromDateStr(updated,format=fmt) except Exception, e: info_string = _utils.formattedException(details=e) toks_fmt = fmt.split() toks = updated.split() if (toks_fmt[-1] == '%Z'): del toks_fmt[-1] del toks[-1] updated = ' '.join(toks) fmt = ' '.join(toks_fmt) try: return _utils.getFromDateStr(updated,format=fmt) except Exception, e: info_string = _utils.formattedException(details=e) #logging.warning(info_string) pass
def backgroundProcess(self,wxParent): '''wxParent is the object instance for the wxPython Frame instance for the app that runs this process or a suitable replacement thereof''' try: wxParent.number = 100 # signal the elapsed read-out to begin working... wxParent.count = 1 # signal the elapsed read-out to begin working... wxParent.append_to_message_Q('Init SalesForce Interface.') from vyperlogix.sf.sf import SalesForceQuery sfQuery = SalesForceQuery(self.__login_dialog__.sf_login_model) from vyperlogix.sf.assets import SalesForceAssets wxParent.append_to_message_Q('Issue SOQL for List of Assets.') assets = SalesForceAssets(sfQuery) cassets = assets.getCurrentAssets() cassets = cassets if not _utils.isBeingDebugged else cassets[0:10] wxParent.number = len(cassets) wxParent.count = 0 for rec in cassets: try: aId = rec['AccountId'] wxParent.append_to_message_Q('Fetching Contact for AccountId of "%s".' % (aId)) contacts = assets.getAccountContacts(aId) wxParent.append_to_message_Q('\tHas %d Contact%s.' % (len(contacts),'(s)' if (len(contacts) > 1) else '')) wxParent.acceptContacts(rec,contacts) except Exception as details: _details = _utils.formattedException(details=details) print >>sys.stdout, _details print >>sys.stderr, _details break finally: self.count += 1 pass except Exception as details: _details = _utils.formattedException(details=details) print >>sys.stdout, _details print >>sys.stderr, _details
def __writeHosts__(self, path=None): if not path: path = self.hosts_path try: if (self.settings is not None and self.settings.has_key('backup') and self.settings['backup'] == True): toks = list(os.path.splitext(path)) toks[-1] += '.backup' path = ''.join(toks) hostsFile = open(path, 'w') for key, value in self.iteritems(): if (key == 'comments'): print >> hostsFile, value if ( not misc.isList(value)) else '\n'.join(value) for key, value in self.iteritems(): if (key not in ['settings', 'comments']): for alias in self.__unique__(value): print >> hostsFile, '{destination}\t{aliases}'.format( destination=key, aliases=alias) hostsFile.flush() hostsFile.close() except IOError, ex: print 'An error occured while trying to write the file:\n{path}\n\nError {message}\n\nWindows Vista/7 users:\nIf enabled, UAC prevents alterations to this file or location.\n\nConsider making a backup file in a different location.'.format( path=path, message=ex.message) print _utils.formattedException(details=ex)
def fget(self): val = False if (callable(self.__callback_developers_check__)): try: val = self.__callback_developers_check__() except Exception as details: print _utils.formattedException(details=details) return val
def sendEmail(self, message, trial=False): """ actually send the email message. message - Message object trial - if set to True, doesn't actually send email. Default: False """ msgTxt = message.message if trial is True: if self.log is not None: self.log.debug('TRIAL email FROM:%s \tTO:%s', message.fromAdd, message.toAddList) self.log.debug('TRIAL email BODY:%s', msgTxt) return {'trial': [message.toAddList, msgTxt]} else: toSet = sets.Set(message.toAddList) ccSet = sets.Set(message.ccAddList) bccSet = sets.Set(message.bccAddList) sendToList = toSet | ccSet | bccSet # union try: mstat = self.mailServer.sendmail( message.fromAdd, sendToList, msgTxt.encode('ascii', 'replace')) toAlias = sendToList info_string = "Sent mail with Subject '%s' to %s" % ( message.subject[:50], toAlias) if self.log is not None: self.log.info(info_string) else: print >> sys.stderr, info_string return mstat except smtplib.SMTPRecipientsRefused, details: info_string = 'Error mail not sent, problem in Recepients %s\n%s' % ( sendToList, _utils.formattedException(details=details)) if self.log is not None: self.log.exception(info_string) else: print >> sys.stderr, info_string return info_string except Exception as details: info_string = 'Error in delivering e-mail to one of %s\n%s' % ( sendToList, _utils.formattedException(details=details)) if self.log is not None: self.log.exception(info_string) self.log.exception(' %s ERROR:%s', Exception, e) else: print >> sys.stderr, info_string return info_string
def EnableChildren(self): for w in self.GetChildren(): try: for ww in w.GetChildren(): try: ww.Enable() except Exception as details: print >>sys.stderr, _utils.formattedException(details=details) except: try: w.Enable() except Exception as details: print >>sys.stderr, _utils.formattedException(details=details)
def __init__(self): self.mongodb_test = settings.MONGODB_TEST self.mongodb_mongoose = settings.SLEEPY_MONGOOSE self.mongodb_service_name = settings.MONGODB_SERVICE_NAME try: self.response = mongodb.SleepyMongoose(self.mongodb_mongoose).__http_gets__(self.mongodb_test) except Exception as ex: self.response = None logging.warning(_utils.formattedException(details=ex)) try: self.results = mongodb.SleepyMongoose(self.mongodb_mongoose).connect() except Exception as ex: self.results = None logging.warning(_utils.formattedException(details=ex)) logging.info('self.mongodb_mongoose=%s, self.mongodb_service_name=%s' % (self.mongodb_mongoose,self.mongodb_service_name))
def sf_query(self, soql='', callback=None): self.__lastError__ = '' if (len(soql) > 0): try: try: _types = self.sfQuery.getObjectsFromSOQL(soql, callback=callback) except Exception as details: self.__lastError__ = _utils.formattedException( details=details) return None return _types except Exception as details: self.__lastError__ = _utils.formattedException(details=details) return None
def links(self, address): file_request = urllib2.Request(address) file_opener = urllib2.build_opener() file_feed = file_opener.open(file_request).read() items = [] file_feed = _utils.ascii_only(file_feed) try: file_xml = minidom.parseString(file_feed) item_nodes = file_xml.getElementsByTagName("url") for item in item_nodes: nodes = [] for node in [ n for n in item.childNodes if (n.nodeName == 'loc') ]: try: nodes.append(node.firstChild.data) except: pass for n in nodes: items.append(n) except Exception as e: info_string = _utils.formattedException(details=e) items.append(info_string) items.append(str(file_feed)) return items
def __terminate__(): from vyperlogix.misc import _utils from vyperlogix.win.WinProcesses import Win32Processes from vyperlogix import misc from vyperlogix.misc import ObjectTypeName __programName__ = (sys.argv[0].split(os.sep)[-1].split('.'))[0] try: p = Win32Processes() pid = p.getProcessIdByName(__programName__) if (misc.isList(pid)) and (len(pid) > 0): pid = pid[0] elif (len(pid) == 0): pid = os.getpid() if (misc.isInteger(pid)): print 'DEBUG: pid="%s"' % (pid) print 'BEGIN:' _utils.terminate() print 'END !!!' else: print 'DEBUG: pid is not an Int because it is "%s" !!!' % (ObjectTypeName.typeClassName(pid)) except Exception as ex: info_string = _utils.formattedException(details=ex) print info_string
def delete(self, obj): self.__lastError__ = '' try: self.session.delete(obj) except Exception as details: from vyperlogix.misc import _utils self.__lastError__ = _utils.formattedException(details=details)
def beginTransaction(self): self.__lastError__ = '' try: self.session.begin() except Exception as details: from vyperlogix.misc import _utils self.__lastError__ = _utils.formattedException(details=details)
def close(self): self.__lastError__ = '' try: self.session.close() except Exception as details: from vyperlogix.misc import _utils self.__lastError__ = _utils.formattedException(details=details)
def fget(self): try: return self.__codec_name__(self.__codec__) except Exception as details: info_string = _utils.formattedException(details=details) print >>sys.stderr, info_string return None
def __codec_name__(self, codec): try: return codec.__name__.lower().replace('_encode','') except Exception as details: info_string = _utils.formattedException(details=details) print >>sys.stderr, info_string return None
def destroy_session(self, session_id): self.__lastError__ = '' try: del self.__sessions__[session_id] except Exception as details: from vyperlogix.misc import _utils self.__lastError__ = _utils.formattedException(details=details)
def updateSalesForceObject(objProxy): try: objProxy.update() except Exception as details: from vyperlogix.misc import _utils info_string = _utils.formattedException(details=details) print >>sys.stderr, info_string
def __handle_file__(a,w,f,out=None): if (callable(callback)): try: time.sleep(1) # mitigate a possible race condition - don't want to consume the file too quickly... LOL callback(a,w,f,output=out) except Exception, ex: print >> sys.stderr, 'EXCEPTION: %s' % (_utils.formattedException(details=ex))
def write(self, s): if (self.f): try: wx.CallAfter(self._appendText, self.f, s) except Exception as details: info_string = _utils.formattedException(details=details) print >> sys.stderr, info_string
def _appendText(self, log, x): try: x = x.strip() print >> sys.stdout, x except Exception as details: _details = _utils.formattedException(details) print >> sys.stderr, _details
def onExit(): if (callable(self.__onExit__)): try: self.__onExit__(self) except Exception as ex: info_string = _utils.formattedException(details=ex) print >> self.__sysout__, info_string
def __init__(self,sfQuery,account,role=roles.MoltenPrivileges.Member,tree=AccountTreeNode(-1,"root",None)): ''' account is the name of the account of the Id of the account. To-Do: Feed this object a COntact Id and let it figure-out the account for the contact. ''' expected_class_name = ObjectTypeName._typeName(AccountTreeNode).split('.')[-1] got_class_name = ObjectTypeName.typeClassName(tree).split('.')[-1] self.__tree__ = tree if (expected_class_name == got_class_name) else None self.__role__ = role if (roles.isValidMoltenUserRole(role)) else None self.__sfQuery__ = sfQuery self.__accountId__ = None self.__account__ = None if (self.__tree__ is None): raise ValueError('Invalid value for tree attribute.') if (self.__role__ is None): raise ValueError('Invalid value for role attribute.') try: n = tree.findForwards(Id=account) if (n is not None): self.__accountId__ = n.Id else: n = tree.findForwards(Name=account) if (n is not None): self.__accountId__ = n.Id if (self.__account__ is None) and (self.__accountId__ is not None): sf_accounts = SalesForceAccounts(self.sfQuery) accounts = sf_accounts.getAccountById(self.accountId) if (sf_accounts.contains_sf_objects(accounts)): self.__account__ = accounts[0] except Exception as details: info_string = _utils.formattedException(details=details) print >>sys.stderr, info_string if (self.__account__ is None): raise ValueError('Invalid value for account attribute, account must be the Id or the Name of the account.')
def get_package_details(browser, _url, url, logging=None): import urllib2 req = urllib2.Request(url) req.add_header("Referer", url.split('?')[0]) browser.open(req) _d = lists.HashedLists2() form_attrs = [] for anchor in browser.links(): try: href = anchor.url toks = [[x.split('=') for x in tt] for tt in [t.split('&') for t in href.split('?')]] d = {} d[toks[0][0][0]] = dict([tuple(t) for t in toks[-1]]) if (d.has_key('/pypi')): dd = lists.HashedLists2(d['/pypi']) if (len(dd) > 1) and (((dd.has_key(':action')) and (dd[':action'] == 'submit_form')) or ((dd.has_key('%3Aaction')) and (dd['%3Aaction'] == 'submit_form'))): _datum = tuple([href, d, anchor.text]) url, d, details = _datum url = '%s%s' % (_url, url) return get_package_details2(browser, _url, url, logging=logging) except Exception as e: info_string = _utils.formattedException(details=e) pass return _d, form_attrs
def _getAccountTree_(self,account,tree=[],skip_ancestors=False): '''Walk-up the tree look for the account that has no parent then locate all children.''' try: if (account['ParentId'] is None): tree.append(account) ancestors = [] # There cannot be any ancestors because this account has no parent and this makes the account the progenitor by default. else: ancestors = self.getAccountAncestors(account,ancestors=[]) if (not skip_ancestors) and (len(ancestors) > 0): d_ancestors = lists.HashedLists2() for ancestor in ancestors: d_ancestors[ancestor['ParentId']] = ancestor progenitor = d_ancestors[None] if (lists.isDict(progenitor)) and (len([node for node in tree if (node['Id'] == progenitor['Id'])]) == 0): tree.append(progenitor) return self._getAccountTree_(progenitor,tree=tree,skip_ancestors=skip_ancestors) else: if (not lists.isDict(account)): return tree children = self.getAccountsByParentId(account['Id']) for child in children: if (lists.isDict(child)) and (len([node for node in tree if (node['Id'] == child['Id'])]) == 0): tree.append(child) self._getAccountTree_(child,tree=tree,skip_ancestors=True) except Exception as details: info_string = _utils.formattedException(details=details) print >>sys.stderr, info_string return tree
def fget(self): _name = 'Log File is NOT Named.' try: _name = self.f.name except AttributeError, details: info_string = _utils.formattedException(details=details) logging.warning(info_string)
def close(self): logging.info('Closing Log for "%s".' % (self.logFileName)) try: self.f.close() except Exception as details: info_string = _utils.formattedException(details=details) logging.warning(info_string)
def get_qry_by_parts(qry, callback=None): items = [] try: num_items = qry.count() one_percent = (num_items / 100) if (one_percent < 200): one_percent = 200 num_items_part = one_percent if (num_items > 10000) else num_items for i in xrange(num_items): item = SQLAgent.instance_as_SmartObject(qry[i]) items.append(item) if (i > 0) and ((i % num_items_part) == 0): if (callable(callback)): try: callback(items) finally: items = [] if (len(items) > 0): if (callable(callback)): try: callback(items) finally: items = [] except Exception as details: print >> sys.stderr, _utils.formattedException(details=details) return items
def dedupeContacts(self, _contacts): from vyperlogix.hash import lists d = lists.HashedLists() for c in _contacts: d[c['Email']] = lists.HashedLists2(c) contacts = [] ascii_only = _utils.ascii_only for k, v in d.iteritems(): if (misc.isList(v)): assets = lists.HashedLists2() for item in v: try: for aKey in item.keys(): item[aKey] = ascii_only(item[aKey]) assets[item['Asset_Id']] = item['Asset_Name'] del item['Asset_Id'] del item['Asset_Name'] except Exception as details: info_string = _utils.formattedException( details=details) appendText(self.__child_frame.textboxLog, info_string) v[0]['Asset_Ids'] = ','.join( misc.sortCopy([item for item in list(set(assets.keys()))])) contacts.append(v[0]) else: try: for aKey in v.keys(): v[aKey] = ascii_only(v[aKey]) except: pass contacts.append(v) return contacts
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 json_to_python(json): d = {} try: from django.utils import simplejson d = simplejson.loads(json) except Exception, e: info_string = _utils.formattedException(details=e) json = {'__error__':info_string}
def dict_to_json(dct): json = '' try: from django.utils import simplejson json = simplejson.dumps(dct) except Exception, e: info_string = _utils.formattedException(details=e) json = {'__error__':info_string}
def handle_data(name,data): try: if (callable(callback)): try: callback(name,data) except: pass #print name,data except Exception, details: from vyperlogix.misc import _utils info_string = _utils.formattedException(details=details)
def queue_email(email_from,email_to,email_subject,email_body,email_body_html,__air_id__,is_html=False,data={},error_symbol=None): ''' See also: settings.py for the following: EMAIL_BACKEND = 'django_mailgun.MailgunBackend' MAILGUN_ACCESS_KEY = 'key-50npnx4bhglbohd-f60k00ottnzop6a8' MAILGUN_SERVER_NAME = 'vyperlogix.com' ''' try: from django.core import mail connection = mail.get_connection() connection.open() email1 = mail.EmailMessage(email_subject, email_body, email_from, [email_to], connection=connection) email1.send() connection.close() except Exception, ex: __queue_email__(email_from,email_to,email_subject,email_body,email_body_html,__air_id__,is_html=True,data=data,error_symbol=error_symbol) if (error_symbol): if (misc.isDict(data) and not data.has_key(error_symbol)): data[error_symbol] = _utils.formattedException(details=ex)
def send_problem_email(self,fromName,email,msg,air_id='',domain_override=''): _current_site_ = domain_override if (domain_override and len(domain_override) > 0) else settings.CURRENT_SITE _current_site = _current_site_.replace('.appspot','').replace('.com','').capitalize() subject = django_utils.render_from_string(__registration_problem_email_subject__,context=Context({ 'fromName': fromName, 'site': _current_site },autoescape=False)) subject = ''.join(subject.splitlines()) # Email subject *must not* contain newlines c = { 'msg': msg, 'fromName': fromName, 'site': _current_site_, 'site_name': _current_site } message = django_utils.render_from_string(__problem_report_email__,context=c) message_html = django_utils.render_from_string(__problem_report_email_html__,context=c) try: queue_email(email,air_sender(air_id),subject,message,message_html,air_id,is_html=True) except Exception, e: info_string = _utils.formattedException(details=e) logging.error('RegistrationManager.create_inactive_user.ERROR --> %s' % (info_string))
def send_activation_email(self,new_user,password,registration_profile,air_id='',domain_override='',prefix='',reason='',data={},error_symbol=None): from vyperlogix.products import keys _current_site_ = domain_override if (domain_override and len(domain_override) > 0) else settings.CURRENT_SITE _current_site = '.'.join([t.capitalize() for t in _current_site_.split('.')]) subject = django_utils.render_from_string(__registration_activation_email_subject__,context=Context({ 'site': _current_site },autoescape=False)) subject = ''.join(subject.splitlines()) # Email subject *must not* contain newlines c = { 'activation_key': keys.encode('%s;%s;%s'%(registration_profile.user.email,password,registration_profile.activation_key)), 'expiration_days': settings.ACCOUNT_ACTIVATION_DAYS, 'site': _current_site if (settings.IS_PRODUCTION_WEB_SERVER) else settings.LOCALHOST, 'site_name': _current_site, 'ssl':'s' if (settings.IS_PRODUCTION_SERVER) else '', } c['activation_symbol'] = '%sactivation/' % ('' if _current_site.endswith('/') else '/') message = django_utils.render_from_string(__registration_activation_email__,context=c) message_html = django_utils.render_from_string(__registration_activation_email_html__,context=c) try: logging.log(logging.INFO,'sender="%s Support <%s>"' % (air_sender(air_id),air_sender(air_id))) queue_email(air_sender(air_id),new_user.email,"Your User Account %sActivation%s for %s" % (prefix,' (%s)'%(reason) if (reason and misc.isString(reason) and (len(reason) > 0)) else '',air_site(air_id)),message,message_html,air_id,is_html=True,data=data,error_symbol=error_symbol) except Exception, e: info_string = _utils.formattedException(details=e) logging.error('RegistrationManager.create_inactive_user.ERROR --> %s' % (info_string))
def get_best_quote2_stops(request,is_removing=False): d = {} dd = {} try: num = 1 count = int(django_utils.get_from_session(request,s_additional_stops_in_transit_count,0)) while (num <= count): key = '%s_%d'%('select_additional_stops_in_transit',num) if (is_removing): del request.session[key] else: value = django_utils.get_from_session(request,key,None) if (value): toks = value.split(',') toks_len = len(toks) - 2 aKey1 = ','.join(toks[0:toks_len]) aKey2 = ','.join(toks[0:toks_len-1]) if (not dd.has_key(aKey1)) and (not dd.has_key(aKey2)): dd[aKey1] = value dd[aKey2] = value d[key] = value num += 1 except Exception, e: d[__error_symbol] = 'WARNING: Cannot retrieve the stops at this time. ('+_utils.formattedException(e)+')'
def send_passwordChg_email(self,user,old_password,password,air_id='',domain_override=''): _current_site_ = domain_override if (domain_override and len(domain_override) > 0) else settings.CURRENT_SITE _current_site = _current_site_.replace('.appspot','').replace('.com','').capitalize() subject = django_utils.render_from_string(__registration_activation_email_subject__,context=Context({ 'site': _current_site },autoescape=False)) subject = ''.join(subject.splitlines()) # Email subject *must not* contain newlines c = { 'key': user.id, 'expiration_days': settings.ACCOUNT_ACTIVATION_DAYS, 'site': _current_site_, 'site_name': _current_site, 'ssl':'s' if (settings.IS_PRODUCTION_SERVER) else '', 'air_id':air_id, 'old_password':old_password, 'password':password, } message = django_utils.render_from_string(__password_change_email__,context=c) message_html = django_utils.render_from_string(__password_change_email_html__,context=c) try: queue_email(air_sender(air_id),user.email,"Password Change Request for %s" % (air_site(air_id)),message,message_html,air_id,is_html=True) except Exception, e: info_string = _utils.formattedException(details=e) logging.error('RegistrationManager.changePassword.ERROR --> %s' % (info_string))
def startup(self): # When ReverseProxy is used the asyncore.loop() handles this part of the process... mySocket = socket.socket ( socket.AF_INET, socket.SOCK_STREAM ) if (logger): logger.info('%s.startup() :: self.ipAddr=[%s], self.port=[%s]' % (self.__class__,self.ipAddr,self.port)) mySocket.bind ( ( self.ipAddr, self.port) ) mySocket.listen ( 1 ) channel, details = mySocket.accept() if (logger): logger.info('(%s) Opened a connection with "%s".' % (self.port,details)) __data__ = '' __filename__ = None __fOut__ = None __chunk_count__ = 0 __re1__ = re.compile("@@@filename=(?P<filename>.*)@@@", re.DOTALL | re.MULTILINE) __re2__ = re.compile("@@@address=(?P<address>.*)@@@", re.DOTALL | re.MULTILINE) while True: try: data = channel.recv(8192) if (data) and (len(data) > 0): for ch in data: if (not __filename__) and (ord(ch) == 0): if (__data__) and (misc.isString(__data__)) and (len(__data__) > 0) and (callable(self.callback)): self.__handler__(__data__) __data__ = '' else: __data__ += ch matches1 = __re1__.search(__data__) matches2 = __re2__.search(__data__) if (matches1): f = matches1.groupdict().get('filename',None) if (f): __filename__ = f dirname = os.path.dirname(__filename__) if (callable(self.callback)): dirname2 = self.__handler__(dirname) if (misc.isIterable(dirname2) and (len(dirname2) > 0)): dirname2 = dirname2[0] if (dirname != dirname2): __filename__ = __filename__.replace(dirname,dirname2) dirname = dirname2 if (not os.path.exists(dirname)): os.makedirs(dirname) __fOut__ = open(__filename__,'wb') __data__ = '' elif (matches2): f = matches2.groupdict().get('address',None) if (f): self.address = f if (logger): logger.debug('Address is "%s".' % (self.address)) __data__ = '' else: i = __data__.find(self.eof) if (__filename__) and (i > -1): __data__ = [ch for ch in __data__] del __data__[i:] __data__ = ''.join(__data__) __fOut__.write(__data__) __fOut__.flush() __fOut__.close() if (callable(self.callback)): self.__handler__(__filename__) if (_utils.is_valid_ip_and_port(self.address)): connect_to_ip,connect_to_port = parse_ip_address_and_port(self.address, default_ip='0.0.0.0', default_port=51555) __writer__ = SocketWriter(connect_to_ip, connect_to_port,retry=True) __writer__.send('@@@delete=%s@@@' % (os.path.basename(__filename__))) __writer__.close() __filename__ = None __fOut__ = None __data__ = '' if (__filename__): __chunk_count__ += 1 if (logger): logger.debug('DEBUG: writing (%s bytes) x (%s) --> "%s"' % (len(__data__),__chunk_count__,__fOut__.name)) __fOut__.write(__data__) __data__ = '' except socket.error: mySocket.close() mySocket = socket.socket ( socket.AF_INET, socket.SOCK_STREAM ) if (logger): logger.info('%s.reconnect() :: self.ipAddr=[%s], self.port=[%s]' % (self.__class__,self.ipAddr,self.port)) mySocket.bind ( ( self.ipAddr, self.port) ) mySocket.listen ( 1 ) channel, details = mySocket.accept() if (logger): logger.info('(%s) Reopened a connection with "%s".' % (self.port,details)) __data__ = '' __filename__ = None __fOut__ = None __chunk_count__ = 0 except Exception, details: info_string = _utils.formattedException(details=details) if (logger): logger.exception('EXCEPTION: %s\n%s' % (details,info_string))
m = DjangoManager(tops=tops,app=__app__) except ImportError, ex: print 'WARNING: Cannot proceed because: %s' % (ex) os._exit(0) from django.core.management import execute_manager try: import settings # Assumed to be in the same directory. except ImportError, details: info_string = _utils.formattedException(details=details) print >>sys.stderr, "Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__ print >>sys.stderr, info_string sys.exit(1) except Exception, details: info_string = _utils.formattedException(details=details) print >>sys.stderr, info_string sys.exit(1) if __name__ == "__main__": _argv = [str(s).strip() for s in sys.argv] print 'sys.argv=%s' % (_argv) try: execute_manager(settings, argv=_argv) except Exception, ex: from vyperlogix.misc import _utils print 'ERROR: %s' % (_utils.formattedException(details=ex))
def __call__(self,*args,**kwargs): super(SalesForceAlchemy, self).__call__(*args,**kwargs) n = self.n.pop() a = list(args) a.append(kwargs) if (n == 'endPoint'): self.__endPoint__ = a elif (n == 'login'): self.__tokenize_password__() self.__sfLoginModel__ = SalesForceLoginModel(username=self.__username__,password=self.__password__) if (isinstance(self.__endPoint__,list)): self.__sfLoginModel__.api_version = self.__api_version__ self.__endPoint__ = self.__endPoint__[0] if (len(self.__endPoint__) > 0) else 'www.salesforce.com' if (self.__endPoint__.find('://') == -1): self.__endPoint__ = self.__sfLoginModel__.get_endpoint(end_point=self.__endPoint__) self.__sfLoginModel__.perform_login(end_point=self.__endPoint__) if (self.isLoggedIn): for t in self.__sfLoginModel__.sfdc.describe_global_response['types']: self.__types__[t] = t self.__sfQuery__ = SalesForceQuery(self.__sfLoginModel__) elif (n == 'username'): self.__username__ = a[0] if (len(a) > 0) else '' elif (n == 'password'): self.__password__ = a[0] if (len(a) > 0) else '' elif (n == 'token'): self.__token__ = a[0] if (len(a) > 0) else '' elif (n == 'fields'): self.__fieldsStack__.append(a) elif (n == 'filter'): self.__filterStack__.append(a) elif (n == 'order_by'): self.__orderByStack__.append(a) elif (n == 'all') or (n == 'count'): try: object_name = self.__objectStack__.pop() except IndexError: raise SalesForceObjectException("Required Object Name was not present. Object Name must appear like this (sf.case.fields('*').filter(Id='value-of-Id').order_by('Name').all()) with each Object Name being present in the target SalesForce Org.") self.object_name = object_name fields = [] names = self.description.fieldnames try: while (len(self.__fieldsStack__) > 0): field = self.__fieldsStack__.pop()[0] if (field == '*'): fields = names break elif (field in names): fields.append(field) else: raise SalesForceFieldException('Field with name of "%s" is not present in the SalesForce object named "%s".' % (field,self.object_name)) except Exception, _details: info_string = _utils.formattedException(details=_details) raise SalesForceParmException('Cannot process the field specifications for object named "%s".\n%s' % (self.object_name,info_string)) self.namesCanonicalized(fields) soql,soql_count = self.__make_soql__() results_count = self.sf_query(soql_count) if (n == 'count'): if (kwargs.has_key('debug')) and (kwargs['debug']): return soql,soql_count,results_count[0] else: return results_count[0] else: if (int(results_count[0]['size'][0]) > 1): pass elif (kwargs.has_key('debug')) and (kwargs['debug']): return soql,soql_count,results_count[0] else: return self.sf_query(soql)
for fname,tup in d.iteritems(): for t in tup: for f in t: _fname = os.sep.join(fname.replace(fp,'').split(os.sep)[1:]) f_new = os.path.join(_dist_folder,_fname) _utils.makeDirs(f_new) try: _f = os.path.join(f_new,f.replace(os.path.join(fp,fname)+os.sep,'')) _utils.makeDirs(_f) if (os.path.splitext(f)[-1] == '.pyc'): print '(Dist) Removing "%s".' % (f) os.rename(f,_f) else: _utils.copyFile(f,_f) except Exception, _details: info_string = _utils.formattedException(details=_details) print '%s %s,%s' % (info_string,f,_f) _deploy_folder = os.path.dirname(os.path.dirname(os.path.dirname(_dist_folder))) _project_folder = os.path.join(_deploy_folder,os.sep.join(['django'])) _deploy_name = _deploy_folder.split(os.sep)[-1] _deploy_folder = os.path.join(_deploy_folder,os.sep.join(['deployments','%s_deployment' % (_deploy_name)])) for root, dirs, files in _utils.walk(_dist_folder,rejecting_re=_rx): for f in files: f1 = os.path.join(root,f) _f = os.sep.join(f1.replace(_dist_folder,'').split(os.sep)[1:]) f2 = os.path.join(_deploy_folder,_f) isCopied = False try: _utils.copyFile(f1,f2)