Exemple #1
0
def bunchify(data, name=None):
    if isinstance(data, Bunch):
        return data
    
    if isinstance(data, list):
        if name == 'rowset':  # we unpack these into a dictionary based on name
            return Bunch({i['name']: bunchify(i, 'rowset') for i in data})
        
        return [bunchify(i) for i in data]
    
    if isinstance(data, dict):
        data = data.copy()
        
        if name == 'row' and 'row' in data:
            # Special case of CCP's silly key:value text.
            pass
        
        if name and name in data and not data.get(name, '').strip():
            data.pop(name)
        
        if name == 'rowset' and 'name' in data:
            data.pop('name')
        
        if len(data) == 1 and isinstance(data.values()[0], dict):
            return bunchify(data.values()[0], data.keys()[0])
        
        result = Bunch({
                k: bunchify(
                        [v] if k in ('row', ) and not isinstance(v, list) else v,
                        k
                    ) for k, v in data.iteritems() if k != 'rowset'
            })
        
        if 'rowset' in data:
            rowset = bunchify(data['rowset'] if isinstance(data['rowset'], list) else [data['rowset']], 'rowset')
            result.update(rowset)
        
        if name == 'rowset':  # rowsets always contain rows, even if there are no results
            result.setdefault('row', [])
        
        return result
    
    if isinstance(data, str):
        data = data.decode('utf-8')
    
    if isinstance(data, (str, unicode)):
        try:
            return number(data)
        except ValueError:
            pass
        
        try:
            return boolean(data)
        except ValueError:
            pass
        
        if ',' in data and (name in ('key', 'columns') or ' ' not in data):
            return array(data)
    
    return data
Exemple #2
0
Fichier : eve.py Projet : Acen/core
def bunchify(data, name=None):
    if isinstance(data, Bunch):
        return data
    
    if isinstance(data, list):
        if name == 'rowset':  # we unpack these into a dictionary based on name
            return Bunch({i['name']: bunchify(i, 'rowset') for i in data})
        
        return [bunchify(i) for i in data]
    
    if isinstance(data, dict):
        data = data.copy()
        
        if name == 'row' and 'row' in data:
            # Special case of CCP's silly key:value text.
            pass
        
        if name and name in data and not data.get(name, '').strip():
            data.pop(name)
        
        if name == 'rowset' and 'name' in data:
            data.pop('name')
        
        if len(data) == 1 and isinstance(data.values()[0], dict):
            return bunchify(data.values()[0], data.keys()[0])
        
        result = Bunch({
                k: bunchify(
                        [v] if k in ('row', ) and not isinstance(v, list) else v,
                        k
                    ) for k, v in data.iteritems() if k != 'rowset'
            })
        
        if 'rowset' in data:
            rowset = bunchify(data['rowset'] if isinstance(data['rowset'], list) else [data['rowset']], 'rowset')
            result.update(rowset)
        
        if name == 'rowset':  # rowsets always contain rows, even if there are no results
            result.setdefault('row', [])
        
        return result
    
    if isinstance(data, str):
        data = data.decode('utf-8')
    
    if isinstance(data, (str, unicode)):
        try:
            return number(data)
        except ValueError:
            pass
        
        try:
            return boolean(data)
        except ValueError:
            pass
        
        if ',' in data and (name in ('key', 'columns') or ' ' not in data):
            return array(data)
    
    return data
Exemple #3
0
    def _find_translations(self, localedir, domain):
        # Allow users to override
        if 'web.locale.languages' in self.config: # pragma: no cover
            return array(self.config['web.locale.languages'])

        translations = []
        for fname in os.listdir(localedir):
            mo_fname = os.path.join(localedir, fname, 'LC_MESSAGES', '%s.mo' % domain)

            if os.path.exists(mo_fname):
                translations.append(fname)

        return translations
Exemple #4
0
def database(app, config):
    # Determine if a database engine has been requested, and load the appropriate middleware.
    if not config.get('db.connections', None):
        return app

    try:
        for connection in array(config.get('db.connections')):
            connection = connection.strip(',')

            engine = config.get('db.%s.engine' % (connection,), 'sqlalchemy')

            try:
                if '.' in engine and ':' in engine:
                    engine = load_object(engine)
                else:
                    try:
                        engine = [i for i in pkg_resources.iter_entry_points(group='webcore.db.engines', name=engine)][0].load()
                    except IndexError:
                        raise Exception('No engine registered with the name: %s' % (engine,))
            except:
                log.exception("Unable to load engine middleware: %r.", engine)
                raise

            try:
                model = config.get('db.%s.model' % (connection,))
                model = load_object(model) if isinstance(model, basestring) else model
            except:
                log.exception("Unable to load application model: %r.", model)
                raise

            try:
                session = config.get('db.%s.session' % (connection,), '%s:session' % (config.get('db.%s.model' % (connection,)),))
                session = load_object(session) if isinstance(session, basestring) else session
            except:
                log.info("No session defined for the %s database connection.", connection)

            app = engine(app, 'db.%s' % (connection,), model, session, **config)

        return app

    except:
        log.exception("Error initializing database connections.")
        raise
Exemple #5
0
    def __init__(self, application, config=dict(), prefix='auth.'):
        self.application = application

        prefix_length = len(prefix)
        our_config = Bunch(default_config.copy())

        for i, j in config.iteritems():
            if i.startswith(prefix):
                our_config[i[prefix_length:]] = j

        our_config.intercept = [i.strip() for i in array(our_config.intercept)]
        our_config.internal = boolean(our_config.internal)

        if our_config.lookup is None:
            raise Exception('You must define an authentication lookup method.')

        our_config.lookup = self.get_method(our_config.lookup)
        our_config.authenticate = self.get_method(our_config.authenticate)

        web.auth.config = our_config
Exemple #6
0
    def test_array(self):
        self.assertEqual(conv.array(None), [])

        self.assertEqual(conv.array([]), [])
        self.assertEqual(conv.array([1, '', 2, 3]), [1, 2, 3])
        self.assertEqual(conv.array([1, '', 3], empty=True), [1, '', 3])
        self.assertEqual(conv.array((4, '', 5)), [4, 5])
        self.assertEqual(conv.array((4, '', 5), empty=True), [4, '', 5])

        self.assertEqual(conv.array("foo,bar"), ["foo", "bar"])
        self.assertEqual(conv.array("foo,,bar", empty=True),
                         ["foo", '', "bar"])
        self.assertEqual(conv.array(uchar()), [uchar()])

        self.assertEqual(conv.array("foo|bar", '|'), ["foo", "bar"])
        self.assertEqual(conv.array("baz |diz", '|', False), ["baz ", "diz"])
        self.assertEqual(conv.array("baz||diz", '|', False, True),
                         ["baz", '', "diz"])

        self.assertEqual(conv.array("baz  diz", None), ["baz", "diz"])
        self.assertEqual(conv.array("baz   diz", None, False, False),
                         ["baz", "diz"])
 def test_array(self):
     self.assertEqual(conv.array(None), [])
     
     self.assertEqual(conv.array([]), [])
     self.assertEqual(conv.array([1, '', 2, 3]), [1, 2, 3])
     self.assertEqual(conv.array([1, '', 3], empty=True), [1, '', 3])
     self.assertEqual(conv.array((4, '', 5)), [4, 5])
     self.assertEqual(conv.array((4, '', 5), empty=True), [4, '', 5])
     
     self.assertEqual(conv.array("foo,bar"), ["foo", "bar"])
     self.assertEqual(conv.array("foo,,bar", empty=True), ["foo", '', "bar"])
     self.assertEqual(conv.array(uchar()), [uchar()])
     
     self.assertEqual(conv.array("foo|bar", '|'), ["foo", "bar"])
     self.assertEqual(conv.array("baz |diz", '|', False), ["baz ", "diz"])
     self.assertEqual(conv.array("baz||diz", '|', False, True), ["baz", '', "diz"])
     
     self.assertEqual(conv.array("baz  diz", None), ["baz", "diz"])
     self.assertEqual(conv.array("baz   diz", None, False, False), ["baz", "diz"])
Exemple #8
0
    def signature(self, line):
        """Determine if this line is a block signature.
        
        Valid block signature format:
            element(class,class#id){style:value;style:...}[lang]...
        
        (There may be one to three trailing periods.  One is standard,
        two indicate a sticky block, three indicate a sticky continuous
        block.)
        """
        block = None
        identifier = None
        classes = list()
        styles = list()
        language = None
        sticky = False
        continuous = False

        line, _, remainder = line.partition(".")
        remainder = remainder.lstrip()

        if not _ or line[0] in (" ", "\t"):
            return None

        if "(" in line:
            block, _, line = line.partition("(")
            idcls, _, line = line.partition(")")
            if " " in idcls:
                return None
            classes, _, identifier = idcls.partition("#")
            classes = array(classes)

        if "{" in line:
            pre, _, line = line.partition("{")
            if not block:
                block = pre
            elif pre:
                return None
            styles, _, line = line.partition("}")
            styles = array(styles, ";")

        if "[" in line:
            pre, _, line = line.partition("[")
            if not block:
                block = pre
            elif pre:
                return None
            language, _, line = line.partition("]")

        if not block:
            if " " in line or not line.isalpha():
                return None

            block = line

        # level, _, remainder = line.rpartition('.')
        #
        # if level and level.strip('.') or not (len(level) <= 2):
        #     # There is stuff left over; this doesn't match a signature!
        #     return None

        # sticky = len(level) >= 1
        # continuous = len(level) == 2

        return (
            Signature(
                block=block,
                id=identifier or None,
                classes=classes,
                styles=styles,
                language=language or None,
                sticky=sticky,
                continuous=continuous,
            ),
            remainder,
        )