def walk(top, options=DictWalkOptions.values_only): from vyperlogix import misc try: __stack__ = [] options = options if ((options) and (options.value)) else DictWalkOptions.values_only while (1): top = [top] if (not misc.isIterable(top)) else [top] if ( misc.isDict(top)) else top for t in top: for k, v in t.iteritems(): __is__ = misc.isDict(v) or misc.isHashedDict(v[0] if ( misc.isIterable(v)) else v) if (__is__): __stack__.append(v) if (options) and (options.value): if (options.value & DictWalkOptions.keys_and_values.value): yield (k, v) elif (options.value & DictWalkOptions.keys_only.value): yield k if (__is__) else v elif (options.value & DictWalkOptions.values_only.value): if (__is__): continue else: yield v else: yield k if (misc.isDict(v)) else v top = __stack__.pop() if (len(__stack__) > 0) else None if (not top): raise StopIteration except: raise StopIteration raise StopIteration
def store_in_bucket_recursive(bucket={}, fp=None): def packit(fp): toks = [t for t in fp.split('/') if t] ret = fp for tok in reversed(toks): ret = {tok: ret} return ret def merge(d1, d2): for k1, v1 in d1.iteritems(): if not k1 in d2: d2[k1] = v1 elif isinstance(v1, dict): merge(v1, d2[k1]) return d2 if (not fp): paths = ['1/2/3', '1/2/4', '1/2/5'] else: paths = [fp] if (not misc.isList(fp)) else fp dicts = [packit(p) for p in paths] merged = bucket if (misc.isDict(bucket)) else {} for d in dicts: merged = merge(merged, d) return merged
def merge(d1, d2): for k1, v1 in d1.iteritems(): if not k1 in d2: d2[k1] = v1 elif misc.isDict(v1): merge(v1, d2[k1]) return d2
def store_in_bucket_recursive(bucket={},fp=None): def packit(fp): toks = [t for t in fp.split('/') if t] ret = fp for tok in reversed(toks): ret = {tok: ret} return ret def merge(d1, d2): for k1,v1 in d1.iteritems(): if not k1 in d2: d2[k1] = v1 elif isinstance(v1, dict): merge(v1, d2[k1]) return d2 if (not fp): paths = ['1/2/3','1/2/4','1/2/5'] else: paths = [fp] if (not misc.isList(fp)) else fp dicts = [packit(p) for p in paths] merged = bucket if (misc.isDict(bucket)) else {} for d in dicts: merged = merge(merged,d) return merged
def __context__(request,data=None): __data__ = { "url": request.META.get('PATH_INFO','/'), "siteurl":"http://djangononrelsample2.vyperlogix.com", "sitename": "djangononrelsample2™", "services": "VyperLogix", "company": "VyperLogix", "sitename2": "The djangononrelsample2™" } if (misc.isDict(data)): for k,v in data.iteritems(): __data__[k] = v return __data__
def process_request(self, request): """ This is run for every request, it checks to see if it can get a defined item out of the cache, if that fails it tries to set it Failing that it decides the server is probably crashed, but goes though and attempts to connect to the server. Failing a connection It will launch a new server. """ if not misc.isDict(self.results) or (not self.results.has_key('ok')) or (self.results['ok'] < 1): # Later-on we will be wanting to make sure the Sleepy Mongoose is also running... logging.warning('mongod service is not running, start it !') self.__restart_service__(self.mongodb_service_name) return None return None
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 __getattr__(self, name): value = super(API, self).__getattr__(name) if (value is None) or (len(value) == 0): # and (name != '/'): _d_ = HashedFuzzySmartLists({}) _values_ = [] for k in self.keys(): if (misc.isDict(super(API, self).__getattr__(k))) and (super( API, self).__getattr__(k).has_key('url')): _k_ = super(API, self).__getattr__(k)['url'].replace( '/' + k.split('@')[0], '') _d_[_k_] = SmartFuzzyObject( super(API, self).__getattr__(k)) l = ListWrapper(_d_.keys()) _name_ = name.split(API.make_key('', ''))[-1] if (not self.__specific__): while (len(_name_) > 0): _list_ = l.findAllContaining(_name_) if ( _name_ != '/') else l.findAllMatching(_name_) _items_ = [ item for item in _list_ if (item.endswith(_name_)) ] x = l.findFirstMatching(_items_[0] if ( len(_items_) > 0) else _name_) if ( (len(_list_) > 0) or (_name_ == '/')) else l.findFirstContaining( _items_[0] if (len(_items_) > 0) else _name_) if (x > -1): for v in _d_[l[x]]: _values_.append(v) break else: x = l.findFirstContaining(_name_) if (x > -1): for v in _d_[l[x]]: _values_.append(v) break else: _l_ = _name_.split('/') del _l_[-2 if (len(_l_[-1]) == 0) else -1] _name_ = '/'.join(_l_) return value if (len(_values_) == 0) else _values_
def send_php_email(url,parms={},is_html=False,data={},error_symbol=None): import urllib,urllib2 content = '' try: __data__ = data # don't worry this line works... data = {} logging.warning('send_php_email().1 --> parms=%s' % (parms)) if (len(parms.keys()) > 0): _expected_keys = ['to','subject','body','altbody'] for k,v in parms.iteritems(): if (k == 'altbody'): data[k] = (v.replace('\n','').replace('\r','').replace("\'",'') if (k in _expected_keys) else '') else: data[k] = (v.replace("\'",'') if (k in _expected_keys) else '') else: data = {'to':'*****@*****.**', 'subject':'This is a test...', 'body':'<p>This is <b>just</b> a test...</p>', 'altbody':'This is just a test...'} logging.warning('send_php_email().2 --> data=%s' % (data)) data = urllib.urlencode(data) user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)' headers = {'User-Agent':user_agent} req = urllib2.Request(url, data, headers) response = urllib2.urlopen(req) content = response.read() logging.warning('send_php_email().3 --> content=%s' % (content)) except Exception, e: toks = ListWrapper(str(e).split()) f = toks.findFirstContaining(']') message = 'send_php_email().ERROR --> "%s".' % (str(e)) message2 = 'send_php_email().ERROR --> "%s".' % (' '.join(toks[f+1:f+1+5]+'...') if (f > -1) else str(e)) if (error_symbol): if (misc.isDict(__data__)): __data__[error_symbol] = message2 logging.warning(message)
def default(request, _get_user=None, domain='localhost', secure_endpoint='http://localhost', insecure_endpoint='http://localhost', air_id=None, air_version={}, apiMap=None, logging=None, callback=None): try: __apiMap__ = apiMap if (apiMap.isAPI) else API({}, secure_endpoint, insecure_endpoint) except: __apiMap__ = API({}, secure_endpoint, insecure_endpoint) qryObj = django_utils.queryObject(request) parms = django_utils.parse_url_parms(request) context = RequestContext(request) __domainName = domain try: _user = __get_user__(request) if ( _get_user is None) else _get_user(request) except: user = __default_superuser__() u = request.session.get('user') if (u): _user = u if (misc.isDict(_user)): _user = SmartFuzzyObject(_user) _is_method_post_ = django_utils.is_method_post(request) is_logging_info = (logging is not None) if (logging is not None): logging.info('(+++) is_logging_info=%s' % (is_logging_info)) is_html = lambda url: (url.endswith('.html')) or (url.endswith('.htm')) try: s_response = '' __error__ = '' url = '/%s%s' % (str('/'.join(parms)), '/' if ((len(parms) > 0) and (not is_html(parms[-1]))) else '') if (is_logging_info): logging.info('(1) url=%s' % (url)) elif (settings.IS_PRODUCTION_SERVER): print '(1) url=%s' % (url) if (url.find('/activate/') > -1): toks = ListWrapper(url.split('/')) i = toks.findFirstMatching('activate') if (i > -1): del toks[i + 1] url = '/'.join(toks) browserAnalysis = django_utils.get_browser_analysis( request, parms, any([])) _current_site = __domainName _current_site = _current_site.replace('.appspot', '').replace('.com', '').lower() aid = parms[-1] if (len(parms) > 0) else '' get_value_from = lambda value, key, default: value[key] if (v.has_key( key)) else default __isUsingChrome__ = (str( browserAnalysis.browserName).lower() == 'Chrome'.lower()) __isUsingOpera__ = (str( browserAnalysis.browserName).lower() == 'Opera'.lower()) __isUsingFireFox__ = (str( browserAnalysis.browserName).lower() == 'FireFox'.lower()) _data = { 'HTTP_USER_AGENT': django_utils.get_from_META(request, 'HTTP_USER_AGENT', ''), 'browserName': browserAnalysis.browserName, 'browserVersion': browserAnalysis.browserVersion, 'isRunningLocal': browserAnalysis.isRunningLocal(request), 'isJavaScriptOptimized': browserAnalysis.isJavaScriptOptimized, 'isUsingUnsupportedBrowser': browserAnalysis.isUsingUnsupportedBrowser, 'isUsingMSIE': browserAnalysis.isUsingMSIE, 'isBrowserWebKit': browserAnalysis.isBrowserWebKit, 'isUsingAndroid': browserAnalysis.isUsingAndroid, 'isUsingChrome': __isUsingChrome__, 'isUsingOpera': __isUsingOpera__, 'isUsingFireFox': __isUsingFireFox__, 'isUsingChromeOrWebKit': (__isUsingChrome__) or (browserAnalysis.isBrowserWebKit), 'qryObj': qryObj, 'serial': str(uuid.uuid4()), 'isShowingFlash': True, 'isShowingTitleBar': True, 'is_superuser': _user.is_superuser, 'secure_endpoint': secure_endpoint, 'insecure_endpoint': insecure_endpoint, 'request_endpoint': secure_endpoint if (django_utils.is_request_HTTPS(request)) else insecure_endpoint, 'version': air_version[air_id] if (air_version[air_id]) else settings.VERSION, 'air_id': air_id, 'apiMap': dict([(' '.join( [str(s).capitalize() for s in k.split('@')[-1].split('_')]), [ get_value_from(v, 'url', '').replace('/' + k.split('@')[0], ''), get_value_from(v, 'isPostRequired', False), get_value_from(v, 'fields', []) ]) for k, v in __apiMap__.asPythonDict().iteritems() if (len(k.split('@')) == 2)]) } try: _data['IS_NOT_LOGGED_IN'] = settings.IS_NOT_LOGGED_IN if ( not _user) else (len(_user.is_authenticated) == 0) if ( misc.isList(_user.is_authenticated) ) else not _user.is_authenticated except: _data['IS_NOT_LOGGED_IN'] = False try: _data['IS_LOGGED_IN'] = not _data['IS_NOT_LOGGED_IN'] except: _data['IS_LOGGED_IN'] = False try: _data['USER_NAME'] = _user.name if ( _user and _data['IS_LOGGED_IN']) else 'Anonymous' except: _data['IS_NOT_LOGGED_IN'] = False try: _data[ 'IS_PRODUCTION_WEB_SERVER'] = settings.IS_PRODUCTION_WEB_SERVER except: _data['IS_PRODUCTION_WEB_SERVER'] = False try: _data[ 'IS_NOT_PRODUCTION_WEB_SERVER'] = settings.IS_NOT_PRODUCTION_WEB_SERVER except: _data['IS_NOT_PRODUCTION_WEB_SERVER'] = False _data['AVAILABLE_AUTH_METHODS'] = [] try: from users.g import AuthMethods for n, v in AuthMethods: e = AuthMethods(n) if (e.value > 0): if (e.value == 1): _data[ 'IS_DJANGO_AUTH_METHOD'] = AuthMethods.django.value > 0 _data['AVAILABLE_AUTH_METHODS'].append( 'IS_DJANGO_AUTH_METHOD') else: k = 'IS_%s_AUTH_METHOD' % (n.upper()) _data[k] = e.value > 0 _data['AVAILABLE_AUTH_METHODS'].append(k) except: _data['IS_DJANGO_AUTH_METHOD'] = True _data['AVAILABLE_AUTH_METHODS'].append('IS_DJANGO_AUTH_METHOD') if (is_logging_info): logging.info('(1.1) _data=%s' % (str(_data))) for k, v in request.session.iteritems(): _data[k] = v if (is_logging_info): logging.info('(1.2) _data=%s' % (str(_data))) air_id = parms[-1].split('.')[0] if ( len(parms) > 0 ) else '' # avoid the key error that would be caused without this line of code... if (is_logging_info): logging.info('(5) air_id=%s' % (air_id)) logging.info('(5.1) _data=%s' % (str(_data))) _is_callable_ = lambda v: any([callable(x.func) for x in v]) if ( misc.isList(v)) else callable(v.func) __apiMap__.__specific__ = is_html(url) m = __apiMap__[url] isUrlMapped = (m != None) and (m != []) and (_is_callable_(m)) if (not isUrlMapped): if (not is_html(url)): url = '/%s%s' % (str('/'.join(parms[0:-1])), '/' if (len(parms[0:-1]) > 0) else '') m = __apiMap__[url] isUrlMapped = (m != None) and (m != []) and (_is_callable_(m)) if (isUrlMapped): air_id = aid if (is_logging_info): logging.info('(6) air_id=%s' % (air_id)) if (settings.IS_PRODUCTION_SERVER): settings.DOMAIN_NAME = settings.APPSPOT_NAME = air_domain[ air_id] else: _m_ = [ k for k in air_version.keys() if ((len(aid) > 0) and ( (aid.lower().find(k.lower()) > -1) or (k.lower().find(aid.lower()) > -1))) or ( k.lower().find(_current_site) > -1) or ( _current_site.lower().find(k.lower()) > -1) ] air_id = _m_[0] if (len(_m_) > 0) else air_id if (is_logging_info): logging.info('(7) air_id=%s, _m_=%s, aid=%s' % (air_id, _m_, aid)) http_host = django_utils.get_from_META(request, 'HTTP_HOST', default='') if (__apiMap__.__secure_endpoint__.find('127.0.0.1') > -1) and (http_host.find('localhost') > -1): http_host = http_host.replace('localhost', '127.0.0.1') http_host = http_host.split(':')[0] _is_http_host_correct_ = True if ( not settings.IS_HTTPS_REQUIRED) else ( __apiMap__.__secure_endpoint__.find(http_host) > -1) _is_request_correct_ = ((not settings.IS_PRODUCTION_SERVER) or (not settings.IS_HTTPS_REQUIRED) or ((settings.IS_PRODUCTION_SERVER) and (django_utils.is_request_HTTPS(request)))) def __resolve_mapping_from_rules__(m, qryObj): for mm in m: _rules_ = [ r for r in [(str(k).split('_'), k) for k in mm.keys()] if (str(r[0][0]).lower() == 'rules') and (len(r[0]) == 2) ] _has_rules_ = any([len(r[0]) == 2 for r in _rules_]) _is_rules_ = False if (_has_rules_): rCnt = 0 for r in _rules_: try: obj = eval(r[0][-1]) if (obj): val = mm[r[-1]] if (val): for k, v in val.iteritems(): if (obj[k] == v): rCnt += 1 m = mm _is_rules_ = True isUrlMapped = True return isUrlMapped, m, _has_rules_ else: _re_ = re.compile(v) if (_re_.match(obj[k])): rCnt += 1 m = mm _is_rules_ = True isUrlMapped = True return isUrlMapped, m, _has_rules_ except: pass if (rCnt < 1): isUrlMapped = False else: m = m[0] isUrlMapped = True return isUrlMapped, m, _has_rules_ return False, m, False isUrlMapped, m, _has_rules_ = __resolve_mapping_from_rules__(m, qryObj) _is_method_correct_ = ((isUrlMapped)) and ( ((m.isPostRequired) and _is_method_post_) or ((not m.isPostRequired) and not _is_method_post_)) if (is_logging_info): logging.info('(7.0) http_host=%s' % (http_host)) logging.info('(7.1) isUrlMapped=%s' % (isUrlMapped)) try: logging.info('(7.2) m.isPostRequired=%s' % (m.isPostRequired)) except: pass logging.info('(7.3) _is_method_post_=%s' % (_is_method_post_)) logging.info('(7.3.1) _is_method_correct_=%s' % (_is_method_correct_)) logging.info('(7.3.2) _is_http_host_correct_=%s, http_host=%s' % (_is_http_host_correct_, http_host)) logging.info('(7.3.3) _is_request_correct_=%s' % (_is_request_correct_)) logging.info('(7.3.4) _has_rules_=%s' % (_has_rules_)) logging.info('(7.4) __apiMap__.__secure_endpoint__=%s' % (__apiMap__.__secure_endpoint__)) logging.info('(7.5) settings.IS_PRODUCTION_SERVER=%s' % (settings.IS_PRODUCTION_SERVER)) logging.info('(7.5.1) settings.IS_HTTPS_REQUIRED=%s' % (settings.IS_HTTPS_REQUIRED)) logging.info('(7.6) django_utils.is_request_HTTPS(request)=%s' % (django_utils.is_request_HTTPS(request))) logging.info( '(7.7) django_utils.get_from_environ(request,\'SERVER_PORT\',80)=%s' % (django_utils.get_from_environ(request, 'SERVER_PORT', 80))) logging.info( '(7.8) django_utils.is_Production()=%s, django_utils.is_Staging()=%s' % (django_utils.is_Production(request), django_utils.is_Staging(request))) if (isUrlMapped) and (_is_method_correct_) and ( _is_http_host_correct_ ) and ( _is_request_correct_ ): # (must be mapped), (must use POST), (must use secure endpoint) and (if production must use SSL). if (is_logging_info): logging.info('(8.0) !!!') try: response = m.func(request, parms, browserAnalysis, air_id, __apiMap__, data=_data) if (is_logging_info): logging.info('(8) response=%s' % (response)) logging.info('(9) settings.APP_SESSION_KEY=%s' % (settings.APP_SESSION_KEY)) django_utils.give_response_session_id_using( request, response, settings.APP_SESSION_KEY) return response except Exception as e: info_string = _utils.formattedException(details=e) logging.info('%s' % (info_string)) return django_utils.render_main_html( request, browserAnalysis, qryObj, data=_data, is_logging_info=is_logging_info, current_site=_current_site, aid=aid, air_id=air_id, logging=logging, context=context) if (air_version[air_id] is None): try: _message = django_utils.get_from_post_or_get( request, 'message', '') if (len(_message) > 0): _data['message'] = _message _url_ = os.sep + os.sep.join( [c for c in url.split('/') if (len(c) > 0)]) _s_ = os.sep.join([settings.MEDIA_ROOT, _url_]) if (os.path.isfile(_s_)) and (os.path.exists(_s_)): _url_ = '/static/' + '/'.join( [c for c in url.split('/') if (len(c) > 0)]) try: return HttpResponseRedirect( _url_ ) # allow the web server to handle this rather than the application server... except: pass return django_static.serve( _s_ ) # if all else fails the application server should handle the request... _url_ = '/'.join( url.split('/')[1 if (url.startswith('/')) else 0:]) if (callable(callback)): try: response = callback(request, _url_, _data) if (isinstance(response, HttpResponseRedirect)): return response except: logging.exception('%s' % (_url_)) return render_to_response(_url_, _data, context_instance=context) except TemplateDoesNotExist, e: try: _url_ += 'index.htm' if (callable(callback)): try: callback(request, _url_, _data, context_instance=context) except: pass return render_to_response(_url_, _data, context_instance=context) except TemplateDoesNotExist, e: try: _url_ += 'l' if (callable(callback)): try: callback(request, _url_, _data, context_instance=context) except: pass return render_to_response(_url_, _data, context_instance=context) except TemplateDoesNotExist, e: info_string = _utils.formattedException(details=e) logging.info('%s' % (info_string))
from django.conf import settings from django.shortcuts import render_to_response from g import __context__ import re import json from vyperlogix import misc from django.contrib.auth.models import AnonymousUser from models import JsonData get_user = lambda r:r.session.get('__user__', AnonymousUser) if (r and misc.isDict(r.session)) else AnonymousUser def default(request): context = __context__(request) current_user = get_user(request) context['IS_NOT_LOGGED_IN'] = current_user is AnonymousUser return render_to_response('main.html', context, content_type="text/html") def data(request): context = __context__(request) current_user = get_user(request) context['IS_NOT_LOGGED_IN'] = current_user is AnonymousUser context['current_user'] = current_user items = JsonData.objects.order_by('statename').all() has_database = len(items) > 0 context['action'] = '/createdata/' if (not has_database) else ''
USE AT YOUR OWN RISK. """ import logging import urllib2 import simplejson from vyperlogix import misc from vyperlogix.misc import _utils from vyperlogix.classes import MagicObject arg0 = lambda args: args[0] if (misc.isIterable(args)) and (len( args) > 0) and (misc.isString(args[0])) else None list0 = lambda args: args[0] if (misc.isIterable(args)) and (len( args) > 0) and ((misc.isList(args[0])) or (misc.isDict(args[0]))) else [] int0 = lambda args: args[0] if (misc.isIterable(args)) and (len( args) > 0) and (misc.isInteger(args[0])) else None bool0 = lambda args: args[0] if (misc.isIterable(args)) and (len( args) > 0) and (misc.isBooleanString(args[0])) else None __only__ = lambda value, target: value if (str(value).lower().capitalize( ) == str(target).lower().capitalize()) else None class SleepyMongoose(MagicObject.MagicObject2): def __init__(self, sleepy_mongoose): ''' See also: https://github.com/kchodorow/sleepy.mongoose/wiki/ ''' toks = sleepy_mongoose.split(':')