Esempio n. 1
0
    def add_async_utility(self, key, config, loop=None):
        if key in self._async_utilities:
            logger.warn(
                f'Utility already registered {key}')
            return

        interface = import_class(config['provides'])
        factory = import_class(config['factory'])
        try:
            utility_object = lazy_apply(
                factory, config.get('settings', {}),
                loop=loop or self._loop)
        except Exception:
            logger.error('Error initializing utility {}'.format(repr(factory)),
                         exc_info=True)
            raise
        provide_utility(utility_object, interface)
        if hasattr(utility_object, 'initialize'):
            task = asyncio.ensure_future(
                lazy_apply(utility_object.initialize, app=self.app),
                loop=loop or self._loop)
        else:
            task = None
            logger.warn(f'No initialize method found on {utility_object} object')
        self.add_async_task(key, task, config)
Esempio n. 2
0
    def add_async_utility(self, key, config, loop=None):
        if key in self._async_utilities:
            logger.warn(f'Utility already registered {key}')
            return

        interface = import_class(config['provides'])
        factory = import_class(config['factory'])
        try:
            utility_object = lazy_apply(factory,
                                        config.get('settings', {}),
                                        loop=loop or self._loop)
        except Exception:
            logger.error('Error initializing utility {}'.format(repr(factory)),
                         exc_info=True)
            raise
        provide_utility(utility_object, interface)
        if hasattr(utility_object, 'initialize'):
            task = asyncio.ensure_future(lazy_apply(utility_object.initialize,
                                                    app=self.app),
                                         loop=loop or self._loop)
        else:
            task = None
            logger.warn(
                f'No initialize method found on {utility_object} object')
        self.add_async_task(key, task, config)
Esempio n. 3
0
 def add_async_utility(self, config, loop=None):
     interface = import_class(config['provides'])
     factory = import_class(config['factory'])
     utility_object = factory(config['settings'], loop=loop)
     provideUtility(utility_object, interface)
     task = asyncio.ensure_future(utility_object.initialize(app=self.app),
                                  loop=loop)
     self.add_async_task(config['provides'], task, config)
Esempio n. 4
0
def create_behaviors_factory(proto_name, proto_definition):

    if proto_definition.get("for", None) is None:
        raise Exception("We need a for interface")
    else:
        for_ = import_class(proto_definition.get("for"))

    if for_ is None:
        raise Exception("Wrong for interface")

    parent_class = import_class(
        proto_definition.get(
            "inherited_class",
            "guillotina.behaviors.instance.AnnotationBehavior"))

    schema_fields, tags = get_fields(
        properties=proto_definition.get("properties"))

    base_interface = proto_definition.get("base_interface", None)
    if base_interface is None:
        base_interface = Interface

    class_interface = InterfaceClass(
        "I" + proto_name,
        (base_interface, ),
        schema_fields,
        __module__="guillotina.contrib.dyncontent.interfaces",
    )

    for field_id, tag in tags.items():
        for tag_id, tag_metadata in tag.items():
            if tag_id in SUPPORTED_DIRECTIVES:
                SUPPORTED_DIRECTIVES[tag_id].apply(class_interface, field_id,
                                                   tag_metadata)

    klass = type(proto_name, (parent_class, ), {})

    klass.__module__ = "guillotina.contrib.dyncontent.behaviors"
    setattr(behaviors, proto_name, klass)

    behavior = {
        "for_": for_,
        "provides": class_interface,
        "data_key": proto_definition.get("data_key", "default"),
        "auto_serialize": proto_definition.get("auto_serialize", True),
        "name": proto_name,
        "name_only": proto_definition.get("name_only", False),
        "title": proto_definition.get("title", ""),
        "marker": proto_definition.get("marker", None),
        "description": proto_definition.get("description", ""),
    }

    configure.register_configuration(klass, behavior, "behavior")
Esempio n. 5
0
 def add_async_utility(self, config, loop=None):
     interface = import_class(config['provides'])
     factory = import_class(config['factory'])
     try:
         utility_object = factory(config['settings'], loop=loop)
     except Exception:
         logger.error('Error initializing utility {}'.format(repr(factory)),
                      exc_info=True)
         raise
     provideUtility(utility_object, interface)
     task = asyncio.ensure_future(utility_object.initialize(app=self.app),
                                  loop=loop)
     self.add_async_task(config['provides'], task, config)
Esempio n. 6
0
    async def create_request(self):
        request = make_request(self.base_request, self.data["req_data"])
        g_task_vars.request.set(request)

        if self.data.get("db_id"):
            root = get_utility(IApplication, name="root")
            db = await root.async_get(self.data["db_id"])
            g_task_vars.db.set(db)
            # Add a transaction Manager to request
            tm = db.get_transaction_manager()
            g_task_vars.tm.set(tm)
            # Start a transaction
            txn = await tm.begin()
            # Get the root of the tree
            context = await tm.get_root(txn=txn)

            if self.data.get("container_id"):
                container = await context.async_get(self.data["container_id"])
                if container is None:
                    raise Exception(
                        f'Could not find container: {self.data["container_id"]}'
                    )
                g_task_vars.container.set(container)
                annotations_container = IAnnotations(container)
                container_settings = await annotations_container.async_get(
                    REGISTRY_DATA_KEY)
                layers = container_settings.get(ACTIVE_LAYERS_KEY, [])
                for layer in layers:
                    try:
                        alsoProvides(request, import_class(layer))
                    except ModuleNotFoundError:
                        pass
                g_task_vars.registry.set(container_settings)
        return request
Esempio n. 7
0
    async def __call__(self):
        """ data input : { 'interface': 'INTERFACE' }"""
        if not hasattr(self.request, 'container_settings'):
            return ErrorResponse(
                'BadRequest',
                _("Not in a container request"),
                status=412)

        data = await self.request.json()
        interface = data.get('interface', None)
        initial_values = data.get('initial_values', {})
        if interface is None:
            return ErrorResponse(
                'InvalidRequest',
                'Non existent Interface',
                status=412)

        registry = self.request.container_settings
        iObject = import_class(interface)
        registry.register_interface(iObject)
        config = registry.for_interface(iObject)

        # Initialize values
        # If its defined on the guillotina.schema default will not be overwritten
        #  you will need to PATCH
        for key, field in get_fields(iObject).items():
            if key in initial_values and getattr(config, key, _marker) == _marker:
                # We don't have a value
                config[key] = initial_values[key]

        return Response(status=201)
Esempio n. 8
0
async def add_initialized(event):
    type_names = []
    behaviors = []

    for type_name, definition in app_settings.get("behaviors", {}).items():
        create_behaviors_factory(type_name, definition)
        behaviors.append(type_name)
    reload_behavior_configuration()

    for type_name, definition in app_settings.get("contents", {}).items():
        create_content_factory(type_name, definition)
        type_names.append(type_name)
    reload_content_configuration()

    for type_name in type_names:
        # Verify its created
        if type_name in FACTORY_CACHE:
            del FACTORY_CACHE[type_name]
        get_cached_factory(type_name)

    for proto_name in behaviors:
        # Verify its created
        interface_name = "guillotina.contrib.dyncontent.interfaces.I" + proto_name
        utility = get_utility(IBehavior, name=interface_name)
        class_interface = import_class(interface_name)
        assert BEHAVIOR_CACHE[interface_name].__identifier__ == interface_name
        utility.interface == class_interface
Esempio n. 9
0
    async def clone_request(self, method, endpoint, payload, headers):
        container = task_vars.container.get()
        container_url = IAbsoluteURL(container, self.request)()
        url = posixpath.join(container_url, endpoint)
        parsed = urlparse(url)
        raw_headers = tuple(
            (k.encode("utf-8"), v.encode("utf-8")) for k, v in headers.items())
        request = self.request.__class__(
            self.request.scheme,
            method,
            parsed.path,
            parsed.query.encode("utf-8"),
            raw_headers,
            client_max_size=self.request._client_max_size,
            send=self.request.send,
            receive=self.request.receive,
            scope=self.request.scope,
        )
        request._state = self.request._state.copy()
        request._read_bytes = payload

        registry = await get_registry(container)
        layers = registry.get(ACTIVE_LAYERS_KEY, [])
        for layer in layers:
            try:
                alsoProvides(request, import_class(layer))
            except ModuleNotFoundError:
                pass
        return request
Esempio n. 10
0
 def del_async_utility(self, config):
     self.cancel_async_utility(config['provides'])
     interface = import_class(config['provides'])
     utility = getUtility(interface)
     gsm = getGlobalSiteManager()
     gsm.unregisterUtility(utility, provided=interface)
     del self._async_utilities[config['provides']]
Esempio n. 11
0
    async def __call__(self):
        """ data input : { 'interface': 'INTERFACE' }"""
        if not hasattr(self.request, 'container_settings'):
            return ErrorResponse('BadRequest', _("Not in a container request"))

        data = await self.request.json()
        interface = data.get('interface', None)
        initial_values = data.get('initial_values', {})
        if interface is None:
            return ErrorResponse('InvalidRequest', 'Non existent Interface')

        registry = self.request.container_settings
        iObject = import_class(interface)
        registry.register_interface(iObject)
        config = registry.for_interface(iObject)

        # Initialize values
        # If its defined on the guillotina.schema default will not be overwritten
        #  you will need to PATCH
        for key, field in get_fields(iObject).items():
            if key in initial_values and getattr(config, key,
                                                 _marker) == _marker:
                # We don't have a value
                config[key] = initial_values[key]

        return Response(response={}, status=201)
Esempio n. 12
0
 def del_async_utility(self, config):
     self.cancel_async_utility(config['provides'])
     interface = import_class(config['provides'])
     utility = get_utility(interface)
     gsm = get_global_components()
     gsm.unregisterUtility(utility, provided=interface)
     del self._async_utilities[config['provides']]
Esempio n. 13
0
    async def __call__(self):
        """ data input : { 'interface': 'INTERFACE' }"""
        registry = await get_registry()
        if registry is None:
            return ErrorResponse("BadRequest",
                                 _("Not in a container request"),
                                 status=412)

        data = await self.request.json()
        interface = data.get("interface", None)
        initial_values = data.get("initial_values", {})
        if interface is None:
            return ErrorResponse("InvalidRequest",
                                 "Non existent Interface",
                                 status=412)

        iObject = import_class(interface)
        registry.register_interface(iObject)
        config = registry.for_interface(iObject)

        # Initialize values
        # If its defined on the guillotina.schema default will not be overwritten
        #  you will need to PATCH
        for key, field in get_fields(iObject).items():
            if key in initial_values and getattr(config, key,
                                                 _marker) == _marker:
                # We don't have a value
                config[key] = initial_values[key]

        await notify(
            RegistryEditedEvent(self.context, registry,
                                {interface: initial_values}))

        return Response(status=201)
Esempio n. 14
0
 async def use_container(self, container: IContainer):
     task_vars.container.set(container)
     registry = await get_registry(container)
     if registry is not None:
         layers = registry.get(ACTIVE_LAYERS_KEY, [])
         for layer in layers:
             alsoProvides(self.request, import_class(layer))
Esempio n. 15
0
 async def use_container(self, container: IResource):
     self.request.container = container
     self.request._container_id = container.id
     annotations_container = IAnnotations(container)
     self.request.container_settings = await annotations_container.async_get(
         REGISTRY_DATA_KEY)
     layers = self.request.container_settings.get(ACTIVE_LAYERS_KEY, [])
     for layer in layers:
         alsoProvides(self.request, import_class(layer))
Esempio n. 16
0
def includeme(root, settings):
    factory = import_class(
        settings.get('mailer', {}).get('utility',
                                       app_settings['mailer']['utility']))
    utility = factory()
    provide_utility(utility, IMailer)

    configure.scan('guillotina_mailer.api')
    configure.scan('guillotina_mailer.utility')
Esempio n. 17
0
 async def use_container(self, container: IResource):
     self.request.container = container
     self.request._container_id = container.id
     annotations_container = IAnnotations(container)
     self.request.container_settings = await annotations_container.async_get(
         REGISTRY_DATA_KEY)
     layers = self.request.container_settings.get(ACTIVE_LAYERS_KEY, [])
     for layer in layers:
         alsoProvides(self.request, import_class(layer))
Esempio n. 18
0
async def traverse(
        request: IRequest, parent: IBaseObject,
        path: Tuple[str, ...]) -> Tuple[IBaseObject, Tuple[str, ...]]:
    """Do not use outside the main router function."""
    if IApplication.providedBy(parent):
        request.application = parent

    if len(path) == 0:
        return parent, path

    assert request is not None  # could be used for permissions, etc

    if not ITraversable.providedBy(parent):
        # not a traversable context
        return parent, path
    try:
        if path[0][0] == "_" or path[0] in (".", ".."):
            raise HTTPUnauthorized()
        if path[0][0] == "@":
            # shortcut
            return parent, path

        if IAsyncContainer.providedBy(parent):
            context = await parent.async_get(path[0], suppress_events=True)
            if context is None:
                return parent, path
        else:
            context = parent[path[0]]
    except (TypeError, KeyError, AttributeError):
        return parent, path

    if IDatabase.providedBy(context):
        task_vars.db.set(context)
        # Add a transaction Manager to request
        tm = context.get_transaction_manager()
        task_vars.tm.set(tm)
        # Start a transaction
        txn = await tm.begin(
            read_only=not app_settings["check_writable_request"](request))
        # Get the root of the tree
        context = await tm.get_root(txn=txn)

    if IContainer.providedBy(context):
        task_vars.container.set(context)
        # make sure to unset before we attempt to load in case
        # there is an existing registry object set on task_vars
        task_vars.registry.set(None)
        registry = await get_registry(context)
        layers = registry.get(ACTIVE_LAYERS_KEY, [])
        for layer in layers:
            try:
                alsoProvides(request, import_class(layer))
            except ModuleNotFoundError:
                logger.error("Can not apply layer " + layer, request=request)

    return await traverse(request, context, path[1:])
Esempio n. 19
0
 async def initialize(self, app):
     self.app = app
     for workflow_name, definition in self.workflows.items():
         factory = create_workflow_factory(workflow_name, definition)
         self.factories[workflow_name] = factory
     for interface_str, workflow in self.workflows_content.items():
         iface = import_class(interface_str)
         provide_adapter(self.factories[workflow],
                         adapts=(iface, ),
                         provides=IWorkflow)
Esempio n. 20
0
def includeme(root, settings):
    mailer_settings = settings.get("mailer") or app_settings.get("mailer")
    factory = import_class(mailer_settings.get("utility"))
    logger.debug(f"Setting Mail Utility: {mailer_settings['utility']}")
    if settings.get("mailer", {}).get("default_sender", None) is None:
        logger.warning(f"No sender mail configured on mailer.default_sender settings")
    utility = factory()
    provide_utility(utility, IMailer)

    configure.scan("guillotina.contrib.mailer.utility")
Esempio n. 21
0
 async def del_async_utility(self, key):
     self.cancel_async_utility(key)
     config = self._async_utilities[key]['config']
     interface = import_class(config['provides'])
     utility = get_utility(interface)
     if hasattr(utility, 'finalize'):
         await lazy_apply(utility.finalize, app=self.app)
     gsm = get_global_components()
     gsm.unregisterUtility(utility, provided=interface)
     del self._async_utilities[key]
Esempio n. 22
0
 async def del_async_utility(self, key):
     self.cancel_async_utility(key)
     config = self._async_utilities[key]['config']
     interface = import_class(config['provides'])
     utility = get_utility(interface)
     if hasattr(utility, 'finalize'):
         await lazy_apply(utility.finalize, app=self.app)
     gsm = get_global_components()
     gsm.unregisterUtility(utility, provided=interface)
     del self._async_utilities[key]
Esempio n. 23
0
 async def initialize(self, app):
     self.app = app
     for workflow_name, definition in self.workflows.items():
         logger.info(f"Registered workflow {workflow_name}")
         factory = create_workflow_factory(workflow_name, definition)
         self.factories[workflow_name] = factory
     for interface_str, workflow in self.workflows_content.items():
         logger.info(f"Linked workflow {workflow} to {interface_str}")
         iface = import_class(interface_str)
         provide_adapter(self.factories[workflow], adapts=(iface,), provides=IWorkflow)
Esempio n. 24
0
async def traverse(request, parent, path):
    """Do not use outside the main router function."""
    if IApplication.providedBy(parent):
        request.application = parent

    if not path:
        return parent, path

    assert request is not None  # could be used for permissions, etc

    if not ITraversable.providedBy(parent):
        # not a traversable context
        return parent, path
    try:
        if path[0][0] == '_' or path[0] in ('.', '..'):
            raise HTTPUnauthorized()
        if path[0][0] == '@':
            # shortcut
            return parent, path

        if IAsyncContainer.providedBy(parent):
            context = await parent.async_get(path[0], suppress_events=True)
            if context is None:
                return parent, path
        else:
            context = parent[path[0]]
    except (TypeError, KeyError, AttributeError):
        return parent, path

    if IDatabase.providedBy(context):
        request._db_write_enabled = app_settings['check_writable_request'](
            request)
        request._db_id = context.id
        # Add a transaction Manager to request
        tm = request._tm = context.get_transaction_manager()
        # Start a transaction
        txn = await tm.begin(request=request)
        # Get the root of the tree
        context = await tm.get_root(txn=txn)

    if IContainer.providedBy(context):
        request._container_id = context.id
        request.container = context
        annotations_container = IAnnotations(request.container)
        request.container_settings = await annotations_container.async_get(
            REGISTRY_DATA_KEY)
        layers = request.container_settings.get(ACTIVE_LAYERS_KEY, [])
        for layer in layers:
            try:
                alsoProvides(request, import_class(layer))
            except ModuleNotFoundError:
                logger.error('Can not apply layer ' + layer, request=request)

    return await traverse(request, context, path[1:])
Esempio n. 25
0
    def __init__(self, context, request, field):
        self.context = context
        self.request = request
        self.field = field

        iface = import_class(app_settings['cloud_storage'])
        alsoProvides(field, iface)

        self.file_storage_manager = get_multi_adapter(
            (context, request, field), IFileStorageManager)
        self.dm = get_adapter(self.file_storage_manager, IUploadDataManager)
Esempio n. 26
0
    def __init__(self, context, request, field):
        self.context = context
        self.request = request
        self.field = field

        iface = import_class(app_settings['cloud_storage'])
        alsoProvides(field, iface)

        self.file_storage_manager = get_multi_adapter(
            (context, request, field), IFileStorageManager)
        self.dm = get_adapter(
            self.file_storage_manager, IUploadDataManager)
Esempio n. 27
0
def includeme(root, settings):
    factory = import_class(
        settings.get('mailer', {}).get('utility',
                                       settings['mailer']['utility']))
    logger.debug(f"Setting Mail Utility: {settings['mailer']['utility']}")
    if settings.get('mailer', {}).get('default_sender', None) is None:
        logger.warning(
            f"No sender mail configured on mailer.default_sender settings")
    utility = factory()
    provide_utility(utility, IMailer)

    configure.scan('guillotina.contrib.mailer.utility')
Esempio n. 28
0
async def traverse(request, parent, path):
    """Do not use outside the main router function."""
    if IApplication.providedBy(parent):
        request.application = parent

    if not path:
        return parent, path

    assert request is not None  # could be used for permissions, etc

    if not ITraversable.providedBy(parent):
        # not a traversable context
        return parent, path
    try:
        if path[0][0] == '_' or path[0] in ('.', '..'):
            raise HTTPUnauthorized()
        if path[0][0] == '@':
            # shortcut
            return parent, path

        if IAsyncContainer.providedBy(parent):
            context = await parent.async_get(path[0], suppress_events=True)
            if context is None:
                return parent, path
        else:
            context = parent[path[0]]
    except (TypeError, KeyError, AttributeError):
        return parent, path

    if IDatabase.providedBy(context):
        request._db_write_enabled = app_settings['check_writable_request'](request)
        request._db_id = context.id
        # Add a transaction Manager to request
        tm = request._tm = context.get_transaction_manager()
        # Start a transaction
        txn = await tm.begin(request=request)
        # Get the root of the tree
        context = await tm.get_root(txn=txn)

    if IContainer.providedBy(context):
        request._container_id = context.id
        request.container = context
        annotations_container = IAnnotations(request.container)
        request.container_settings = await annotations_container.async_get(REGISTRY_DATA_KEY)
        layers = request.container_settings.get(ACTIVE_LAYERS_KEY, [])
        for layer in layers:
            try:
                alsoProvides(request, import_class(layer))
            except ModuleNotFoundError:
                logger.error('Can not apply layer ' + layer, request=request)

    return await traverse(request, context, path[1:])
Esempio n. 29
0
 async def del_async_utility(self, key: str):
     self.cancel_async_utility(key)
     config = self._async_utilities[key]["config"]
     interface = import_class(config["provides"])
     if "name" in config:
         utility = get_utility(interface, name=config["name"])
     else:
         utility = get_utility(interface)
     if hasattr(utility, "finalize"):
         await lazy_apply(utility.finalize, app=self.app)
     gsm = get_global_components()
     gsm.unregisterUtility(utility, provided=interface)
     del self._async_utilities[key]
Esempio n. 30
0
    async def clone_request(self, method, endpoint, payload, headers):
        container_url = IAbsoluteURL(self.request.container, self.request)()
        url = posixpath.join(container_url, endpoint)
        parsed = urlparse(url)
        dct = {'method': method, 'url': URL(url), 'path': parsed.path}
        dct['headers'] = CIMultiDict(headers)
        dct['raw_headers'] = tuple(
            (k.encode('utf-8'), v.encode('utf-8')) for k, v in headers.items())

        message = self.request._message._replace(**dct)

        payload_writer = mock.Mock()
        payload_writer.write_eof.side_effect = noop
        payload_writer.drain.side_effect = noop

        protocol = mock.Mock()
        protocol.transport = test_utils._create_transport(None)
        protocol.writer = payload_writer

        request = self.request.__class__(
            message,
            SimplePayload(payload),
            protocol,
            payload_writer,
            self.request._task,
            self.request._loop,
            client_max_size=self.request._client_max_size,
            state=self.request._state.copy(),
            scheme=self.request.scheme,
            host=self.request.host,
            remote=self.request.remote)

        request._db_write_enabled = True
        request._db_id = self.request._db_id
        request._tm = self.request._tm
        request._txn = self.request._txn

        request._container_id = self.context.id
        request.container = self.context
        annotations_container = IAnnotations(self.context)
        request.container_settings = await annotations_container.async_get(
            REGISTRY_DATA_KEY)
        layers = request.container_settings.get(ACTIVE_LAYERS_KEY, [])
        for layer in layers:
            try:
                alsoProvides(request, import_class(layer))
            except ModuleNotFoundError:
                pass
        request._futures = self.request._futures
        return request
Esempio n. 31
0
    def add_async_utility(
        self,
        key: str,
        config: typing.Dict,
        loop: typing.Optional[asyncio.AbstractEventLoop] = None
    ) -> typing.Optional[typing.Tuple[typing.Any,
                                      typing.Optional[asyncio.Future]]]:
        if key in self._async_utilities:
            logger.warn(f'Utility already registered {key}')
            return None

        interface = import_class(config['provides'])
        factory = import_class(config['factory'])
        try:
            utility_object = lazy_apply(factory,
                                        config.get('settings', {}),
                                        loop=loop or self._loop)
        except Exception:
            logger.error('Error initializing utility {}'.format(repr(factory)),
                         exc_info=True)
            raise
        alsoProvides(utility_object, interface)
        kw = {}
        if 'name' in config:
            kw['name'] = config['name']
        provide_utility(utility_object, interface, **kw)
        if hasattr(utility_object, 'initialize'):
            func = lazy_apply(utility_object.initialize, app=self.app)

            task = asyncio.ensure_future(notice_on_error(key, func),
                                         loop=loop or self._loop)
            self.add_async_task(key, task, config)
            return utility_object, task
        else:
            logger.info(
                f'No initialize method found on {utility_object} object')
            return None
Esempio n. 32
0
async def traverse(request, parent, path):
    """Do not use outside the main router function."""
    if IApplication.providedBy(parent):
        request.application = parent

    if not path:
        return parent, path

    assert request is not None  # could be used for permissions, etc

    if not ITraversable.providedBy(parent):
        # not a traversable context
        return parent, path
    try:
        if path[0].startswith('_'):
            raise HTTPUnauthorized()
        if IAsyncContainer.providedBy(parent):
            context = await parent.async_get(path[0])
        else:
            context = parent[path[0]]
    except (TypeError, KeyError, AttributeError):
        return parent, path

    if IDatabase.providedBy(context):
        request._db_write_enabled = False
        request._db_id = context.id
        # Create a transaction Manager
        request._tm = context.new_transaction_manager()
        # Start a transaction
        try:
            await request._tm.begin(request=request)
        except asyncpg.exceptions.UndefinedTableError:
            pass
        # Get the root of the tree
        context = await request._tm.root()

    if ISite.providedBy(context):
        request._site_id = context.id
        request.site = context
        annotations_container = IAnnotations(request.site)
        request.site_settings = await annotations_container.async_get(
            REGISTRY_DATA_KEY)
        layers = request.site_settings.get(ACTIVE_LAYERS_KEY, [])
        for layer in layers:
            alsoProvides(request, import_class(layer))

    return await traverse(request, context, path[1:])
Esempio n. 33
0
 def __init__(self, context, request, field):
     iface = import_class(app_settings['cloud_storage'])
     alsoProvides(field, iface)
     self.real_file_manager = get_multi_adapter((context, request, field),
                                                IFileManager)
Esempio n. 34
0
def create_content_factory(proto_name, proto_definition):
    parent_interface = import_class(
        proto_definition.get("inherited_interface",
                             "guillotina.interfaces.content.IFolder"))
    parent_class = import_class(
        proto_definition.get("inherited_class", "guillotina.content.Folder"))

    schema_fields, tags = get_fields(
        properties=proto_definition.get("properties"))

    class_interface = InterfaceClass(
        "I" + proto_name,
        (parent_interface, ),
        schema_fields,
        __module__="guillotina.contrib.dyncontent.interfaces",
    )

    for field_id, tag in tags.items():
        for tag_id, tag_metadata in tag.items():
            if tag_id in SUPPORTED_DIRECTIVES:
                if tag_metadata is None:
                    SUPPORTED_DIRECTIVES[tag_id].apply(class_interface,
                                                       field_id)
                elif isinstance(tag_metadata, dict):
                    SUPPORTED_DIRECTIVES[tag_id].apply(class_interface,
                                                       field_id,
                                                       **tag_metadata)
                elif isinstance(tag_metadata, list):
                    SUPPORTED_DIRECTIVES[tag_id].apply(class_interface,
                                                       field_id, *tag_metadata)
                elif tag_id == "fieldset":
                    SUPPORTED_DIRECTIVES[tag_id].apply(class_interface,
                                                       field_id, tag_metadata)
                elif isinstance(tag_metadata, str):
                    SUPPORTED_DIRECTIVES[tag_id].apply(
                        class_interface, **{field_id: tag_metadata})

    klass = type(proto_name, (parent_class, ), {})

    klass.__module__ = "guillotina.contrib.dyncontent.contents"
    setattr(contents, proto_name, klass)

    behaviors = []
    for bhr in proto_definition.get("behaviors", []):
        if bhr in BEHAVIOR_CACHE:
            behaviors.append(BEHAVIOR_CACHE[bhr])
        else:
            raise Exception(f"Behavior not found {bhr}")

    contenttype = {
        "schema":
        class_interface,
        "type_name":
        proto_name,
        "allowed_types":
        proto_definition.get("allowed_types", []),
        "add_permission":
        proto_definition.get("add_permission", "guillotina.AddContent"),
        "behaviors":
        behaviors,
    }

    utility = query_utility(IResourceFactory, name=proto_name)
    if utility is not None:
        sm = get_global_components()
        sm.unregisterUtility(utility, IResourceFactory, proto_name)

    configure.register_configuration(klass, contenttype, "contenttype")
Esempio n. 35
0
def get_fields(*, properties: typing.Dict[str, typing.Dict]):
    fields: typing.Dict[str, typing.Any] = {}
    tags: typing.Dict[str, typing.Any] = {}

    for prop_id, prop in properties.items():

        params: typing.Dict[str, typing.Any] = {}

        field_class = typing.cast(
            typing.Callable, import_class(typing.cast(str, prop.get("type"))))

        # Vocabulary
        get_vocabulary(prop, params)

        # Required
        params["required"] = prop.get("required", False)

        # Title
        params["title"] = prop.get("title")

        widget = prop.get("widget", None)
        if widget:
            params["widget"] = widget

        # Schema
        schema = prop.get("schema", None)
        if schema:
            params["schema"] = json.dumps(schema)

        # Value type
        value_type = prop.get("value_type", None)
        if value_type:
            value_class = typing.cast(typing.Callable,
                                      import_class(value_type))
            params["value_type"] = value_class(required=False,
                                               title=params["title"] +
                                               " value")

        # Default
        if prop.get("default", None) is not None:
            params["default"] = prop.get("default")

        # Index
        index = prop.get("index", None)
        if index:
            tags.setdefault(prop_id, {})["index"] = index

        write_permission = prop.get("write_permission", None)
        if write_permission:
            tags.setdefault(prop_id, {})["write_permission"] = write_permission

        metadata = prop.get("metadata", None)
        if metadata:
            tags.setdefault(prop_id, {})["metadata"] = None

        read_permission = prop.get("read_permission", None)
        if read_permission:
            tags.setdefault(prop_id, {})["read_permission"] = read_permission

        fields[prop_id] = field_class(**params)  # noqa

    #
    return fields, tags
Esempio n. 36
0
    async def create_request(self):
        req_data = self.data['req_data']
        url = req_data['url']
        parsed = urlparse(url)
        dct = {
            'method':
            req_data['method'],
            'url':
            yarl.URL(url),
            'path':
            parsed.path,
            'headers':
            CIMultiDict(req_data['headers']),
            'raw_headers':
            tuple((k.encode('utf-8'), v.encode('utf-8'))
                  for k, v in req_data['headers'].items())
        }

        message = self.base_request._message._replace(**dct)

        payload_writer = mock.Mock()
        payload_writer.write_eof.side_effect = noop
        payload_writer.drain.side_effect = noop

        protocol = mock.Mock()
        protocol.transport = test_utils._create_transport(None)
        protocol.writer = payload_writer

        request = self.base_request.__class__(
            message,
            EmptyPayload(),
            protocol,
            payload_writer,
            self.task,
            self.task._loop,
            client_max_size=self.base_request._client_max_size,
            state=self.base_request._state.copy())
        g_task_vars.request.set(request)
        request.annotations = req_data.get('annotations', {})

        if self.data.get('db_id'):
            root = get_utility(IApplication, name='root')
            db = await root.async_get(self.data['db_id'])
            g_task_vars.db.set(db)
            # Add a transaction Manager to request
            tm = db.get_transaction_manager()
            g_task_vars.tm.set(tm)
            # Start a transaction
            txn = await tm.begin()
            # Get the root of the tree
            context = await tm.get_root(txn=txn)

            if self.data.get('container_id'):
                container = await context.async_get(self.data['container_id'])
                if container is None:
                    raise Exception(
                        f'Could not find container: {self.data["container_id"]}'
                    )
                g_task_vars.container.set(container)
                annotations_container = IAnnotations(container)
                container_settings = await annotations_container.async_get(
                    REGISTRY_DATA_KEY)
                layers = container_settings.get(ACTIVE_LAYERS_KEY, [])
                for layer in layers:
                    try:
                        alsoProvides(request, import_class(layer))
                    except ModuleNotFoundError:
                        pass
                g_task_vars.registry.set(container_settings)
        return request