Exemplo n.º 1
0
    def __call__(self, wrapped):

        def callback(scanner, name, ob):

            setattr(wrapped, '__meta__',
                    {'tablename': None,
                     'alias': 't{}'.format(self._counter),
                     'database': self.database,
                     'collation': self.collation,
                     'columns': None,     # column name in the database
                     'attributes': None,  # map col name to attribute name
                     # Populate on column descriptors
                     'primary_key': {},
                     'pkv': None,
                     'foreign_keys': {},
                     })

            self.__class__._counter += 1

            if not self.name:
                self.name = re.sub('(.)([A-Z][a-z]+)', r'\1_\2',
                                   wrapped.__name__)
                self.name = re.sub('([a-z0-9])([A-Z])', r'\1_\2',
                                   self.name).lower()
            wrapped.__meta__['tablename'] = self.name

            meta.register(self.database, self.name, wrapped)

        venusian.attach(wrapped, callback, category='aiorm')
        return wrapped
Exemplo n.º 2
0
Arquivo: role.py Projeto: ecreall/dace
    def __call__(self, wrapped):
        def callback(scanner, name, ob):
            ob.name = self.name
            ob.islocal = self.islocal
            ob.superiors = list(ob.superiors)
            ob.superiors.extend(self.superiors)
            ob.superiors = list(set(ob.superiors))
            def get_allsuperiors(role_ob):
                superiors = list(role_ob.superiors)
                for sup in role_ob.superiors:
                    superiors.extend(get_allsuperiors(sup))

                return list(set(superiors))

            ob.all_superiors = list(ob.all_superiors)
            ob.all_superiors.extend(get_allsuperiors(ob))
            ob.all_superiors = list(set(ob.all_superiors))
            for role in ob.all_superiors:
                role.lowers = list(set(getattr(role, 'lowers', [])))
                role.lowers.append(ob)
                role.lowers = list(set(role.lowers))

            for role in getattr(ob, 'lowers', self.lowers):
                role.superiors = list(role.superiors)
                role.superiors.append(ob)
                role.superiors = list(set(role.superiors))
                role.all_superiors = list(role.all_superiors)
                role.all_superiors.append(ob)
                role.all_superiors.extend(ob.all_superiors)
                role.all_superiors = list(set(role.all_superiors))

            DACE_ROLES[ob.name] = ob
 
        venusian.attach(wrapped, callback)
        return wrapped
Exemplo n.º 3
0
 def decorate(factory):
     def callback(scanner, factory_name, factory):
         scanner.config.action(('location', name), set_location,
                               args=(scanner.config, name, factory),
                               order=PHASE2_CONFIG)
     venusian.attach(factory, callback, category='pyramid')
     return factory
Exemplo n.º 4
0
def _add_argument(function, *args, **kwargs):
    """Add arguments to a function.

    This adds a :mod:`venusian` callback to the given function in the
    ``serverstf:arguments`` category that, when scanned, will attempt to
    add the given command line argument to the corresponding subcommand.

    :param function: the function to add the callback to. This function must
        be decorated by :func:`subcommand`.
    :param args: passed to :meth:`argparse.ArgumentParser.add_argument`.
    :param kwargs: passed to :meth:`argparse.ArgumentParser.add_argument`.

    :return: the given ``function``.
    """

    def callback(scanner, name, obj):  # pylint: disable=unused-argument,missing-docstring
        subcommands = getattr(obj, _SUBCOMMANDS, None)
        if not subcommands:
            raise CLIError("Can't set CLI arugments for "
                           "{} as it is not a subcommand".format(obj))
        for command in subcommands:
            command.arguments.append((args, kwargs))

    # Depth 2 is required so that we can use this from within decorators.
    venusian.attach(function, callback,
                    category=__package__ + ":arguments", depth=2)
    return function
Exemplo n.º 5
0
 def decorator(wrapped):
     def callback(scanner, name, obj):
         for scheme in schemes:
             scanner.config.registry.registerUtility(
                     obj, IStorageFactory, scheme)
     venusian.attach(wrapped, callback)
     return wrapped
Exemplo n.º 6
0
    def __call__(self, wrapped):
        def callback(scanner, name, ob):
            if ob.classification_id not in CLASSIFICATIONS:
                CLASSIFICATIONS[ob.classification_id] = ob

        venusian.attach(wrapped, callback)
        return wrapped
Exemplo n.º 7
0
    def decorate(checker):
        def callback(scanner, factory_name, factory):
            scanner.config.add_audit_checker(
                checker, item_type, condition, frame)

        venusian.attach(checker, callback, category='auditor')
        return checker
Exemplo n.º 8
0
Arquivo: app.py Projeto: io41/morepath
 def __new__(mcl, name, bases, d):
     testing_config = d.get('testing_config')
     d['registry'] = Registry(name, bases, testing_config,
                              d.get('variables', []))
     result = super(AppMeta, mcl).__new__(mcl, name, bases, d)
     venusian.attach(result, callback)
     return result
Exemplo n.º 9
0
    def attach(self, action, cfg=None, depth=1):
        action.info = self
        if action.hash is None:
            action.hash = self.hash

        data = getattr(self.module, ATTACH_ATTR, None)
        if data is None:
            data = AttachData()
            setattr(self.module, ATTACH_ATTR, data)

        if cfg is None and action.hash in data:
            raise TypeError(
                "Directive registered twice: %s" % (action.discriminator,))
        data[action.hash] = action

        def callback(context, name, ob):
            config = context.config.with_package(self.module)

            config.info = action.info
            config.action(
                action.discriminator, self._runaction, (action, config),
                introspectables=action.introspectables,
                order=action.order)

        venusian.attach(data, callback, category='ptah', depth=depth+1)

        if cfg is not None:
            cfg.action(
                action.discriminator,
                self._runaction, (action, cfg),
                introspectables=action.introspectables, order=action.order)
Exemplo n.º 10
0
    def decorator(wrapped):

        def callback(scanner, name, ob):
            scanner.registry.add(name, ob, internals, pass_msg)

        venusian.attach(wrapped, callback)
        return wrapped
Exemplo n.º 11
0
def method(method_class):
    """Decorator to use to mark an API method.

    When invoking L{Registry.scan} the classes marked with this decorator
    will be added to the registry.

    @param method_class: The L{Method} class to register.
    """

    def callback(scanner, name, method_class):
        if method_class.actions is not None:
            actions = method_class.actions
        else:
            actions = [name]

        if method_class.versions is not None:
            versions = method_class.versions
        else:
            versions = [None]

        for action in actions:
            for version in versions:
                scanner.registry.add(method_class,
                                     action=action,
                                     version=version)

    from venusian import attach
    attach(method_class, callback, category="method")
    return method_class
Exemplo n.º 12
0
    def __call__(self, wrapped):
        def callback(scanner, name, ob):
            ob.component_id = self.component_id
            ob.loading_component = self.loading_component
            ob.on_demand = self.on_demand
            ob.delegate = self.delegate
            old_call = ob.update

            def update(self):
                if not self.params('load_view') or (self.on_demand and self.params('on_demand') != 'load'):
                    component = self.loading_component(
                        self.context, self.request,
                        component_id=self.component_id)
                    component.wrapper_template = ob.wrapper_template
                    component.title = ob.title
                    component.viewid = ob.viewid
                    component.view_icon = getattr(ob, 'view_icon', '')
                    component.counter_id = getattr(ob, 'counter_id', '')
                    component.css_class = ob.css_class + ' async-component-container'
                    component.container_css_class = ob.container_css_class + \
                        ' async-component'
                    component.isactive = getattr(ob, 'isactive', False)
                    return component.update()

                return old_call(self)

            ob.update = update
            ON_LOAD_VIEWS[self.component_id] = ob

        venusian.attach(wrapped, callback, category='site_widget')
        return wrapped
Exemplo n.º 13
0
 def __call__(self, wrapped):
     decorator = self
     def callback(scanner, name, obj):  #pylint: disable-msg=W0613
         if hasattr(scanner, 'plugin_registry'):
             scanner.plugin_registry.add('administration_link', decorator.link_text, PluginRegistryItem(decorator))
     venusian.attach(wrapped, callback, category='pvs.plugins')
     return wrapped
Exemplo n.º 14
0
 def wrapped_grokker(wrapped):
     def callback(scanner, name, ob):
         kw = make_arguments(directives, wrapped)
         # XXX give better feedback identifying grokker in
         # case of a TypeError
         grokker(scanner, name, ob, **kw)
     venusian.attach(wrapped, callback, category=self.category)
     return wrapped
Exemplo n.º 15
0
    def deco(wrapped):
        def callback(scanner, _name, wrapped):
            wrapped = functools.partial(wrapped, scanner.config)
            event.listen(target, identifier, wrapped, *args, **kwargs)

        venusian.attach(wrapped, callback)

        return wrapped
Exemplo n.º 16
0
def subcommand(wrapped):
    """This decorator makes a function becomes a subcommand

    """
    def callback(scanner, name, ob):
        scanner.subcommands[ob.name] = ob
    venusian.attach(wrapped, callback, category='subcommands')
    return wrapped
Exemplo n.º 17
0
    def deco(wrapped):
        def callback(scanner, name, wrapped):
            celery_app = scanner.config.registry["celery.app"]
            celery_app.task(**kwargs)(wrapped)

        venusian.attach(wrapped, callback)

        return wrapped
Exemplo n.º 18
0
def scan(package):
    """Scan the package for registered venusian callbacks"""
    scope, module, f_locals, f_globals, codeinfo = \
        venusian.advice.getFrameInfo(sys._getframe(1))
    venusian.attach(
        module,  # module, where scan was called
        lambda scanner, name, ob, package=package: _scan(scanner, package)
    )
Exemplo n.º 19
0
Arquivo: config.py Projeto: pbs/flowy
        def conf_deco(func):

            def callback(venusian_scanner, *_):
                """This gets called by venusian at scan time."""
                self.register(venusian_scanner, key, func)

            venusian.attach(func, callback, category=self.category)
            return func
Exemplo n.º 20
0
    def wrapper(wrapped):

        def callback(scanner, name, obj):
            celery_app = scanner.config.registry.celery_app
            celery_app.task(**kwargs)(obj)

        venusian.attach(wrapped, callback)
        return wrapped
Exemplo n.º 21
0
    def _wrapped(cls):

        def callback(scanner, obj_name, obj):
            registry = scanner.config.registry
            registry["filters"].append((name, obj))

        venusian.attach(cls, callback)
        return cls
Exemplo n.º 22
0
def doc_type(cls):
    def callback(scanner, _name, item):
        types_ = scanner.config.registry.setdefault("search.doc_types", set())
        types_.add(item)

    venusian.attach(cls, callback)

    return cls
 def dec(mapper):
     def callback(scanner, name, ob):
         config = scanner.config
         todict_adapter = mapper_adapter(ob)
         config.set_todict(cls, todict_adapter, name=register_name)
     venusian.attach(mapper, callback, 
                     category='pyramid')
     return mapper
Exemplo n.º 24
0
Arquivo: dec.py Projeto: adevore/irc3
def plugin(wrapped):
    """register a class as plugin"""
    def callback(context, name, ob):
        bot = context.bot
        bot.get_plugin(ob)
    assert isinstance(wrapped, type)
    venusian.attach(wrapped, callback, category='irc3')
    return wrapped
Exemplo n.º 25
0
def i18n_domain(domain):
    """Set i18n domain for the current context"""
    scope, module, f_locals, f_globals, codeinfo = \
        venusian.advice.getFrameInfo(sys._getframe(1))
    venusian.attach(
        module,  # module, where i18n_domain was called
        lambda scanner, name, ob, domain=domain:
        setattr(scanner.context, 'i18n_domain', domain)
    )
Exemplo n.º 26
0
    def decorate(Item):

        def callback(scanner, factory_name, factory):
            scanner.config.action(('collection', name), set_collection,
                                  args=(scanner.config, Item.AbstractCollection, name, Item),
                                  kw=kw,
                                  order=PHASE2_CONFIG)
        venusian.attach(Item, callback, category='pyramid')
        return Item
Exemplo n.º 27
0
def attach(identity, category, task_factory, *a, **kw):
    p_task_factory = partial(task_factory, *a, **kw)

    def callback(venusian_scanner, f_name, obj):
        logger.info("Found %r as '%s' while scanning.",
                    task_factory, f_name)
        f = partial(p_task_factory, f_name=f_name)
        venusian_scanner.registry[identity(f_name, obj)] = f
    venusian.attach(task_factory, callback, category=category)
Exemplo n.º 28
0
 def __call__(self, schema):
     ct = make_content_type(
         schema, schema.__name__, schema.__module__, meta=self.meta,
         property_factory=self.property_factory
     )
     def callback(scanner, name, ob):
         scanner.limone.register_content_type(ct)
     venusian.attach(ct, callback, category='limone')
     return ct
Exemplo n.º 29
0
 def decorator(cls):
     ct = make_content_type(
         schema, cls.__name__, cls.__module__, (cls,), self.meta,
         property_factory=self.property_factory
     )
     def callback(scanner, name, ob):
         scanner.limone.register_content_type(ct)
     venusian.attach(ct, callback, category='limone')
     return ct
Exemplo n.º 30
0
    def __call__(self, wrapped):

        def callback(scanner, name, ob):
            task_ = Task(scanner.driver, wrapped, **self.task_options)
            log.info('Register task {}'.format(task_.name))
            scanner.driver.register_task(task_)

        venusian.attach(wrapped, callback, category='apium')
        return wrapped
Exemplo n.º 31
0
    def __init__(self,
                 name,
                 path,
                 description=None,
                 cors_policy=None,
                 depth=1,
                 **kw):
        self.name = name
        self.path = path
        self.description = description
        self.cors_expose_all_headers = True
        self._cors_enabled = None

        if cors_policy:
            for key, value in cors_policy.items():
                kw.setdefault('cors_' + key, value)

        for key in self.list_arguments:
            # default_{validators,filters} and {filters,validators} don't
            # have to be mutables, so we need to create a new list from them
            extra = to_list(kw.get(key, []))
            kw[key] = []
            kw[key].extend(getattr(self, 'default_%s' % key, []))
            kw[key].extend(extra)

        self.arguments = self.get_arguments(kw)
        for key, value in self.arguments.items():
            # avoid squashing Service.decorator if ``decorator``
            # argument is used to specify a default pyramid view
            # decorator
            if key != 'decorator':
                setattr(self, key, value)

        if hasattr(self, 'factory') and hasattr(self, 'acl'):
            raise KeyError("Cannot specify both 'acl' and 'factory'")

        # instantiate some variables we use to keep track of what's defined for
        # this service.
        self.defined_methods = []
        self.definitions = []

        # add this service to the list of available services
        SERVICES.append(self)

        # register aliases for the decorators
        for verb in ('GET', 'POST', 'PUT', 'DELETE', 'OPTIONS', 'PATCH'):
            setattr(self, verb.lower(),
                    functools.partial(self.decorator, verb))

        if VENUSIAN:
            # this callback will be called when config.scan (from pyramid) will
            # be triggered.
            def callback(context, name, ob):
                config = context.config.with_package(info.module)
                config.add_cornice_service(self)

            info = venusian.attach(self,
                                   callback,
                                   category='pyramid',
                                   depth=depth)
Exemplo n.º 32
0
def user_model(wrapped):
    def callback(context, name, ob):
        set_user_model(context.config.registry, ob)

    info = venusian.attach(wrapped, callback, category='procyon')

    return wrapped
Exemplo n.º 33
0
def extend(func):
    """Allow to extend a bot:

    Create a module with some useful routine:

    .. literalinclude:: ../examples/myextends.py
    ..
        >>> import sys
        >>> sys.path.append('examples')
        >>> from irc3 import IrcBot
        >>> IrcBot.defaults.update(async=False, testing=True)

    Now you can use those routine in your bot::

        >>> bot = IrcBot()
        >>> bot.include('myextends')
        >>> print(bot.my_usefull_function(1))
        my_usefull_function(*(1,))
        >>> print(bot.my_usefull_method(2))
        my_usefull_method(*(2,))

    """
    def callback(context, name, ob):
        obj = context.context
        if info.scope == 'class':
            f = getattr(obj.get_plugin(ob), func.__name__)
        else:
            f = func
        setattr(obj, f.__name__, f.__get__(obj, obj.__class__))

    info = venusian.attach(func, callback, category='irc3.extend')
    return func
Exemplo n.º 34
0
        def _api(func):
            _api_kw = api_kw.copy()
            docstring = func.__doc__

            for validator in validators:
                func = _apply_validator(func, validator)

                if validator.__doc__ is not None:
                    if docstring is not None:
                        docstring += validator.__doc__.strip()
                    else:
                        docstring = validator.__doc__.strip()

            def callback(context, name, ob):
                config = context.config.with_package(info.module)
                self._define(config, method)
                config.add_apidoc((self.route_pattern, method), docstring,
                                  self.renderer, self)
                config.add_view(view=ob, route_name=self.route_name, **_api_kw)

            info = venusian.attach(func, callback, category='pyramid')

            if info.scope == 'class':
                # if the decorator was attached to a method in a class, or
                # otherwise executed at class scope, we need to set an
                # 'attr' into the settings if one isn't already in there
                if 'attr' not in kw:
                    kw['attr'] = func.__name__

            kw['_info'] = info.codeinfo  # fbo "action_method"

            return func
Exemplo n.º 35
0
    def __call__(self, wrapped):
        settings = self.__dict__.copy()

        def callback(context, name, ob):
            config = context.config.with_package(info.module)
            config.add_panel(panel=ob, **settings)
            ADVERTISING_CONTAINERS[self.name] = {
                'title': ob.title,
                'description': ob.description,
                'order': ob.order,
                'validator': ob.validator,
                'tags': ob.tags
                # TODO add validator ob.validator
            }

        info = venusian.attach(wrapped, callback, category='pyramid_layout')

        if info.scope == 'class':
            # if the decorator was attached to a method in a class, or
            # otherwise executed at class scope, we need to set an
            # 'attr' into the settings if one isn't already in there
            if settings['attr'] is None:
                settings['attr'] = wrapped.__name__

        settings['_info'] = info.codeinfo  # fbo "action_method"
        return wrapped
Exemplo n.º 36
0
    def __init__(cls, name, bases, attrs):
        def cb(context, name, ob):
            config = context.config.with_package(info.module)
            configurator = cls.view_configurator_class(config, cls)
            list_route = configurator.configure_list_view()
            edit_route = configurator.configure_edit_view()
            new_route = configurator.configure_new_view()
            delete_confirm_route = configurator.configure_delete_confirm_view()

            cls.routes = {
                'list': list_route,
                'edit': edit_route,
                'new': new_route,
                'delete_confirm': delete_confirm_route,
            }
        if '__abstract__' not in attrs:
            have_attrs = set(attrs)
            need_attrs = set(('schema', 'model', 'url_path'))
            if have_attrs & need_attrs != need_attrs:
                missing = need_attrs - (have_attrs & need_attrs)
                raise AttributeError(
                    "Invalid configuration. The following attributes are "
                    "missing and need to be defined for a complete "
                    "configuration : %s" % ", ".join(missing))
            if cls.view_configurator_class is not None:
                info = venusian.attach(cls, cb)

            # Initialize mutable defaults
            cls.actions = []
Exemplo n.º 37
0
    def __call__(self, view):
        def callback(context, name, ob):
            config = context.config
            config.kotti_snippets(self.name, self.slots)

        info = venusian.attach(view, callback, category='kotti_snippets')
        return view
Exemplo n.º 38
0
    def __init__(
        self,
        resource_name,
        plural_name=None,
        singular=False,
        documentation="",
        acl=None,
    ):
        super(Resource, self).__init__(
            resource_name,
            plural_name,
            singular,
            documentation,
            acl,
        )
        self.info = venusian.attach(self, self.callback)

        # define REST decorators
        if not self.singular:
            iter_methods = iter(self.methods)

        if self.singular:
            iter_methods = iter(self.singular_methods)

        for method in iter_methods:
            setattr(self, method, functools.partial(self.decorator, method))
Exemplo n.º 39
0
def attach_command(func, depth=2, **predicates):
    commands = predicates.pop('commands', 'irc3.plugins.command.Commands')
    category = predicates.pop('venusian_category', 'irc3.plugins.command')

    def callback(context, name, ob):
        obj = context.context
        if info.scope == 'class':
            callback = func.__get__(obj.get_plugin(ob), ob)
        else:
            callback = utils.wraps_with_context(func, obj)
        plugin = obj.get_plugin(utils.maybedotted(commands))
        predicates.update(module=func.__module__)
        cmd_name = predicates.get('name', func.__name__)
        if not plugin.case_sensitive:
            cmd_name = cmd_name.lower()
        plugin[cmd_name] = (predicates, callback)
        aliases = predicates.get('aliases', None)
        if aliases is not None:
            for alias in aliases:
                plugin.aliases[alias] = cmd_name
            obj.log.debug('Register command %r %r', cmd_name, aliases)
        else:
            obj.log.debug('Register command %r', cmd_name)

    info = venusian.attach(func, callback, category=category, depth=depth)
Exemplo n.º 40
0
        def __call__(self, func):
            """ Registers the wrapped func as a path function that executes
                at the terminal path in each path in `self.paths`.
            """

            # callback runs synchronously when venusian.Scanner.scan is called
            # in graph.scan.
            def callback(scanner, name, obj):
                """ Register path function with contexts
                """
                _func = func  # enclose the reference for use in conditionals
                for path in self._paths:
                    path.execute = _func

            venusian.attach(func, callback)
            return func
Exemplo n.º 41
0
        def __call__(self, wrapped):
            """Attach the decorator with Venusian"""
            args = self.args
            kwargs = self.kwargs

            def callback(scanner, _name, wrapped):
                """Register a view; called on config.scan"""
                config = scanner.config

                # pylint: disable=W0142
                add_simple_route(config, self.prefixed_route_path, wrapped, *args, route_kwargs=dict(traverse=self.prefixed_route_path), **kwargs)

                request_method = kwargs.get("request_method", "GET")
                registry = config.registry
                registry.getUtility(IRouteRegistry).register(namespace, self.route_path, request_method, kwargs.get("api",{}))

            info = venusian.attach(wrapped, callback)

            if info.scope == 'class':  # pylint:disable=E1101
                # if the decorator was attached to a method in a class, or
                # otherwise executed at class scope, we need to set an
                # 'attr' into the settings if one isn't already in there
                if kwargs.get('attr') is None:
                    kwargs['attr'] = wrapped.__name__
            return wrapped
Exemplo n.º 42
0
def root(factory):
    """ Set the root
    """
    def set_root(config, factory):
        root = factory(config.registry)
        config.registry[ROOT] = root

    def callback(scanner, factory_name, factory):
        scanner.config.action(('root', ),
                              set_root,
                              args=(scanner.config, factory),
                              order=PHASE1_5_CONFIG)

    venusian.attach(factory, callback, category='pyramid')

    return factory
Exemplo n.º 43
0
    def __call__(self, wrapped):
        def callback(scanner: Scanner, name: str, cls):
            registry: ServiceRegistry = getattr(scanner, 'registry')

            # Later we can do some dataclass field sniffing on singletons
            instance = cls()

            # If there is a for_ use it, otherwise, register for the same
            # class as the instance
            for_ = self.for_ if self.for_ else cls
            registry.register_singleton(
                instance, for_, context=self.context, name=self.name
            )

        attach(wrapped, callback, category='wired')
        return wrapped
Exemplo n.º 44
0
    def __call__(self, wrapped):
        from venusian import attach

        def callback(scanner: Scanner, name: str, cls):
            registry: ServiceRegistry = getattr(scanner, 'registry')

            register_dataclass(
                registry,
                cls,
                for_=self.for_,
                context=self.context,
                # name=self.name,
            )

        attach(wrapped, callback, category='wired_component')
        return wrapped
Exemplo n.º 45
0
    def __call__(self, wrapped):
        def callback(context, name, ob):
            cfg = context.config.with_package(info.module)
            add_fieldpreview(cfg, self.cls, ob)

        info = venusian.attach(wrapped, callback, category='ptah.form')
        return wrapped
Exemplo n.º 46
0
    def __call__(self, wrapped):
        """Attach the decorator with Venusian"""
        args = self.args
        kwargs = self.kwargs

        def callback(scanner, _name, wrapped):
            """Register a view; called on config.scan"""
            config = scanner.config

            # Default to not appending slash
            if not "append_slash" in kwargs:
                append_slash = False

            # pylint: disable=W0142
            add_simple_route(config, self.path, wrapped, *args, **kwargs)

        info = venusian.attach(wrapped, callback)

        if info.scope == 'class':  # pylint:disable=E1101
            # if the decorator was attached to a method in a class, or
            # otherwise executed at class scope, we need to set an
            # 'attr' into the settings if one isn't already in there
            if kwargs.get('attr') is None:
                kwargs['attr'] = wrapped.__name__

        return wrapped
Exemplo n.º 47
0
    def __init__(self, name='', parent=None):
        super(App, self).__init__()
        self.name = name
        self.root_model = None
        self.root_obj = None
        self.child_apps = {}
        self.parent = parent
        self.traject = Traject()
        if self.parent is not None:
            parent.add_child(self)

        # allow being scanned by venusian
        def callback(scanner, name, obj):
            scanner.config.action(self, self)

        venusian.attach(self, callback)
Exemplo n.º 48
0
    def wrapper(klass):
        services = {}

        if 'collection_path' in kw:
            prefixes = ('collection_', '')
        else:
            prefixes = ('', )

        for prefix in prefixes:

            # get clean view arguments
            service_args = {}
            for k in list(kw):
                if k.startswith('collection_'):
                    if prefix == 'collection_':
                        service_args[k[len(prefix):]] = kw[k]
                elif k not in service_args:
                    service_args[k] = kw[k]

            # create service
            service_name = prefix + klass.__name__.lower()
            service = services[service_name] = Service(name=service_name,
                                                       depth=2,
                                                       **service_args)

            # initialize views
            for verb in ('get', 'post', 'put', 'delete', 'options', 'patch'):

                view_attr = prefix + verb
                meth = getattr(klass, view_attr, None)

                if meth is not None:
                    # if the method has a __views__ arguments, then it had
                    # been decorated by a @view decorator. get back the name of
                    # the decorated method so we can register it properly
                    views = getattr(meth, '__views__', [])
                    if views:
                        for view_args in views:
                            service.add_view(verb,
                                             view_attr,
                                             klass=klass,
                                             **view_args)
                    else:
                        service.add_view(verb, view_attr, klass=klass)

        setattr(klass, '_services', services)

        if VENUSIAN:

            def callback(context, name, ob):
                # get the callbacks registred by the inner services
                # and call them from here when the @resource classes are being
                # scanned by venusian.
                for service in services.values():
                    config = context.config.with_package(info.module)
                    config.add_cornice_service(service)

            info = venusian.attach(klass, callback, category='pyramid')
        return klass
Exemplo n.º 49
0
    def decorator(wrapped):
        def callback(scanner, name, ob):
            try:
                testfixtures = scanner.testfixtures
            except AttributeError:
                return
            logger.debug('scanned %s.%s as %r', ob.__module__, ob.__name__,
                         args)
            if args in testfixtures.registry:
                logger.warning(
                    'duplicated testfixture found for %r',
                    args,
                )
            testfixtures.registry[args] = ob

        venusian.attach(wrapped, callback, category='testfixture')
        return wrapped
Exemplo n.º 50
0
    def __call__(self, wrapped):
        def callback(context, name, ob):
            config = context.config.with_package(info.module)
            config.add_renderer_adapter(self.type_or_iface, ob, **settings)

        info = venusian.attach(wrapped, callback)
        settings = {'_info': info.codeinfo}
        return wrapped
Exemplo n.º 51
0
    def _inner(func):
        proxy = TaskProxy(func)

        def callback(scanner, name, task_proxy):
            config = scanner.config

            def register():
                registry = config.registry
                celery = get_celery(registry)
                celery_task = celery.task(task_proxy.original_func, *args,
                                          **kwargs)
                proxy.bind_celery_task(celery_task)

            config.action('bind_celery_task - %s' % name, register)

        venusian.attach(proxy, callback, category='pyramid')
        return proxy
Exemplo n.º 52
0
    def __call__(self, wrapped):
        def callback(scanner, name, ob):
            provides = self.provides
            if self.direct:
                component = ob
                if self.provides is None:
                    provides = list(implementedBy(component))[0]
            else:
                component = ob(**self.kw)
                if self.provides is None:
                    provides = list(providedBy(component))[0]

            scanner.config.registry.registerUtility(component, provides,
                                                    self.name)

        venusian.attach(wrapped, callback)
        return wrapped
Exemplo n.º 53
0
    def __call__(self, wrapped):
        settings = self.__dict__.copy()

        ##
        # Register view method defaults for the game class
        wrapped.__view_defaults__ = {
            "context": wrapped,
            "route_name": "traversal",
            "renderer": "json",
            "http_cache": 0
        }
        ##

        def callback(context, name, ob):
            name = name.lower()  # game id is its class name in lowercase
            config = context.config.with_package(info.module)

            logger.info("Registering game '%s'." % name)

            # Register game so that sessions will be able to find it
            config.registry.registerAdapter(
                ob, name=name, required=(IApplication,), provided=IGame)

            # Register main template for the game
            if settings.get("add_view", True):
                config.add_route(name, "/%s/" % name, request_method="GET")
                config.add_view(route_name=name, renderer="%s.html" % name)

            # Register game specific static assets
            if settings.get("add_asset_views", True):
                dirname = os.path.dirname(info.module.__file__)
                try:
                    resources = map(lambda x: os.path.join(dirname, x),
                                    os.listdir(dirname))
                except OSError:
                    resources = ()

                for path in filter(lambda x: os.path.isfile(x), resources):
                    basename = os.path.basename(path)
                    config.add_route(path, "/%s/%s" % (name, basename),
                                     request_method="GET")
                    if path.endswith('.js') or path.endswith('.css'):
                        #print 'register', path
                        config.add_view(route_name=path,
                                        view=static_file(path),
                                        http_cache=3600)
                    else:
                        config.add_view(route_name=path,
                                        view=static_file(path))
                for path in filter(lambda x: os.path.isdir(x), resources):
                    #print 'static register', path
                    basename = os.path.basename(path)
                    config.add_static_view("%s/%s" % (name, basename),
                                           path=path, cache_max_age=3600)

        info = venusian.attach(wrapped, callback, category="pyramid")

        return wrapped
Exemplo n.º 54
0
    def __call__(self, callable):
        def callback(context, name, callable):
            config = context.config.with_package(info.module)
            config.add_deserializer(self.content_type, callable, **settings)

        info = venusian.attach(callable, callback)
        settings = {'_info': info.codeinfo}

        return callable
Exemplo n.º 55
0
    def __init__(self,
                 name,
                 path=None,
                 description=None,
                 cors_policy=None,
                 depth=1,
                 pyramid_route=None,
                 **kw):
        self.name = name
        self.path = path
        self.pyramid_route = pyramid_route

        if not self.path and not self.pyramid_route:
            raise TypeError('You need to pass path or pyramid_route arg')

        self.description = description
        self.cors_expose_all_headers = True
        self._cors_enabled = None

        if cors_policy:
            for key, value in cors_policy.items():
                kw.setdefault('cors_' + key, value)

        for key in self.list_arguments:
            # default_{validators,filters} and {filters,validators} don't
            # have to be mutables, so we need to create a new list from them
            extra = to_list(kw.get(key, []))
            kw[key] = []
            kw[key].extend(getattr(self, 'default_%s' % key, []))
            kw[key].extend(extra)

        self.arguments = self.get_arguments(kw)
        for key, value in self.arguments.items():
            # avoid squashing Service.decorator if ``decorator``
            # argument is used to specify a default pyramid view
            # decorator
            if key != 'decorator':
                setattr(self, key, value)

        if hasattr(self, 'acl'):
            raise ConfigurationError("'acl' is not supported")

        # instantiate some variables we use to keep track of what's defined for
        # this service.
        self.defined_methods = []
        self.definitions = []

        # add this service to the list of available services
        SERVICES.append(self)

        # this callback will be called when config.scan (from pyramid) will
        # be triggered.
        def callback(context, name, ob):
            config = context.config.with_package(info.module)
            config.add_cornice_service(self)

        info = venusian.attach(self, callback, category='pyramid', depth=depth)
Exemplo n.º 56
0
    def __call__(self, wrapped):
        def callback(context, name, ob):
            cfg = context.config.with_package(info.module)
            add_template_filter(cfg, self.template, ob, self.name,
                                self.description)

        info = venusian.attach(wrapped, callback, category='djed.renderer')

        return wrapped
Exemplo n.º 57
0
    def wrapper(wrapped):
        info = venusian.attach(wrapped, callback, category="pyramid")

        # Support use as a class method decorator.
        # Taken from Pyramid's `view_config` decorator implementation.
        if info.scope == "class":
            if settings.get("attr") is None:
                settings["attr"] = wrapped.__name__

        return wrapped
Exemplo n.º 58
0
    def __call__(self, wrapped):
        original_name = wrapped.__name__
        self._settings["original_name"] = original_name
        if self._settings["method_name"] is None:
            self._settings["method_name"] = original_name

        self.info = venusian.attach(wrapped,
                                    self.register,
                                    category='extdirect')
        return wrapped
Exemplo n.º 59
0
    def __call__(self, cls):

        def callback(context, name, cls):
            config = context.config.with_package(info.module)
            directive = getattr(config, self.directive_name)
            directive(self.resource_path, cls, **settings)

        info = venusian.attach(cls, callback)
        settings = {'_info': info.codeinfo}
        return cls
Exemplo n.º 60
0
 def __call__(self, cls):
     self.info = venusian.attach(cls, self.callback, category='pyramid')
     self.view_class = cls
     self.__doc__ = cls.__doc__
     methods = self.singular_methods if self.singular else self.methods
     views = inspect.getmembers(
         cls, lambda m: inspect.ismethod(m) and m.__name__ in methods)
     for name, view in views:
         self.views[name] = ViewInfo(view, self.info, name, {})
     return cls