How to use the gramex.transforms.build_transform function in gramex

To help you get started, we’ve selected a few gramex examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github gramener / gramex / gramex / handlers / functionhandler.py View on Github external
def setup(cls, headers={}, methods=['GET', 'POST'], **kwargs):
        super(FunctionHandler, cls).setup(**kwargs)
        # Don't use cls.info.function = build_transform(...) -- Python treats it as a method
        cls.info = {}
        cls.info['function'] = build_transform(kwargs, vars={'handler': None},
                                               filename='url: %s' % cls.name)
        cls.headers = headers
        for method in (methods if isinstance(methods, (tuple, list)) else [methods]):
            setattr(cls, method.lower(), cls._get)
github gramener / gramex / gramex / handlers.py View on Github external
def initialize(self, **kwargs):
        self.function = build_transform(kwargs, vars='handler')
        self.headers = kwargs.get('headers', {})
        self.redirect_url = kwargs.get('redirect', None)
github gramener / gramex / gramex / handlers / authhandler.py View on Github external
if recaptcha is not None:
            if 'key' not in recaptcha:
                app_log.error('%s: recaptcha.key missing', cls.name)
            elif 'key' not in recaptcha:
                app_log.error('%s: recaptcha.secret missing', cls.name)
            else:
                recaptcha.setdefault('action', 'login')
                cls.auth_methods['recaptcha'] = cls.check_recaptcha

        # Set up post-login actions
        cls.actions = []
        if action is not None:
            if not isinstance(action, list):
                action = [action]
            for conf in action:
                cls.actions.append(build_transform(
                    conf, vars=AttrDict(handler=None),
                    filename='url:%s:%s' % (cls.name, conf.function)))
github gramener / gramex / gramex / config.py View on Github external
def _calc_value(val, key):
    '''
    Calculate the value to assign to this key.

    If ``val`` is not a dictionary that has a ``function`` key, return it as-is.

    If it has a function key, call that function (with specified args, kwargs,
    etc) and allow the ``key`` parameter as an argument.

    If the function is a generator, the first value is used.
    '''
    if hasattr(val, 'get') and val.get('function'):
        from .transforms import build_transform
        function = build_transform(val, vars={'key': None}, filename='config:%s' % key)
        for result in function(key):
            if result is not None:
                return result
        return val.get('default')
    else:
        return _substitute_variable(val)
github gramener / gramex / gramex / handlers / datahandler.py View on Github external
driver = kwargs.get('driver')
        cls.driver_name = driver
        if driver == 'sqlalchemy':
            cls.driver_method = cls._sqlalchemy
            # Create a cached metadata store for SQLAlchemy engines
            cls.meta = sa.MetaData()
        elif driver == 'blaze':
            cls.driver_method = cls._blaze
        else:
            raise NotImplementedError('driver=%s is not supported yet.' % driver)

        posttransform = kwargs.get('posttransform', {})
        cls.posttransform = []
        if 'function' in posttransform:
            cls.posttransform.append(
                build_transform(
                    posttransform, vars=AttrDict(content=None),
                    filename='url:%s' % cls.name))
github gramener / gramex / gramex / pptgen / __init__.py View on Github external
def register(config):
    """Function to register a new `command` to command list."""
    global COMMANDS_LIST
    resister_command = config.pop('register', {})
    if not isinstance(resister_command, (dict,)):
        raise ValueError('Register should be a dict like object')
    for command_name, command_function in resister_command.items():
        if command_name not in COMMANDS_LIST:
            if not isinstance(command_function, (dict,)):
                command_function = {'function': command_function}
            _vars = {'shape': None, 'spec': None, 'data': None}
            COMMANDS_LIST[command_name] = build_transform(command_function, vars=_vars)
github gramener / gramex / gramex / pptgen / __init__.py View on Github external
dest = prs.slides.add_slide(new_slide) if copy_slide else None
    mapping = {}
    for shape in collection:
        if shape.name not in change:
            copy_slide_elem(shape, dest)
            continue

        spec = change[shape.name]
        if shape.name not in mapping:
            mapping[shape.name] = 0

        if spec.get('data'):
            if not isinstance(spec['data'], (dict,)):
                spec['data'] = {'function': '{}'.format(spec['data']) if not isinstance(
                    spec['data'], (str, six.string_types,)) else spec['data']}
            shape_data = build_transform(
                spec['data'], vars={'data': None, 'handler': None})(data=data, handler=handler)[0]
        else:
            if isinstance(data, (dict, AttrDict,)) and 'handler' in data:
                data.pop('handler')
            shape_data = copy.deepcopy(data)

        if isinstance(shape_data, (dict, AttrDict,)):
            shape_data['handler'] = handler

        if spec.get('stack'):
            shape_data = shape_data[mapping[shape.name]]
        mapping[shape.name] = mapping[shape.name] + 1
        # If the shape is a group, apply spec to each sub-shape
        if is_group(shape):
            sub_shapes = SlideShapes(shape.element, collection)
            change_shapes(sub_shapes, spec, shape_data, handler)
github gramener / gramex / gramex / pptgen / commands.py View on Github external
def compile_function(spec, key, data, handler):
    '''A function to compile configuration.'''
    if key not in spec:
        return None
    _vars = {'_color': None, 'data': None, 'handler': None}
    if not isinstance(spec[key], (dict,)):
        spec[key] = {'function': '{}'.format(spec[key])}
    elif isinstance(spec[key], (dict,)) and 'function' not in spec[key]:
        spec[key] = {'function': '{}'.format(spec[key])}
    args = {'data': data, 'handler': handler, '_color': _color}
    return build_transform(spec[key], vars=_vars)(**args)[0]
github gramener / gramex / gramex / handlers / formhandler.py View on Github external
if 'id' in dataset and not isinstance(dataset['id'], list):
                dataset['id'] = [dataset['id']]
            # Convert function: into a data = transform(data) function
            conf = {
                'function': dataset.pop('function', None),
                'args': dataset.pop('args', None),
                'kwargs': dataset.pop('kwargs', None)
            }
            if conf['function'] is not None:
                fn_name = '%s.%s.transform' % (cls.name, key)
                dataset['transform'] = build_transform(
                    conf, vars={'data': None, 'handler': None}, filename=fn_name, iter=False)
            # Convert modify: and prepare: into a data = modify(data) function
            for fn, fn_vars in cls.function_vars.items():
                if fn in dataset:
                    dataset[fn] = build_transform(
                        conf={'function': dataset[fn]},
                        vars=fn_vars,
                        filename='%s.%s.%s' % (cls.name, key, fn), iter=False)