How to use the guillotina.event.notify function in guillotina

To help you get started, we’ve selected a few guillotina 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 plone / guillotina / guillotina / commands / testdata.py View on Github external
tm = db.get_transaction_manager()
        task_vars.db.set(db)
        tm = db.get_transaction_manager()
        txn = await tm.begin()

        container = await db.async_get(self.arguments.container)
        if container is None:
            container = await create_content("Container", id=self.arguments.container, title="Test Data")
            container.__name__ = self.arguments.container
            await db.async_set(self.arguments.container, container)
            await container.install()
            # Local Roles assign owner as the creator user
            roleperm = IPrincipalRoleManager(container)
            roleperm.assign_role_to_principal("guillotina.Owner", "root")

            await notify(ObjectAddedEvent(container, db, container.__name__))
            try:
                await tm.commit(txn=txn)
            except ConflictIdOnContainer:
                # ignore id conflicts
                await tm.abort(txn=txn)
            txn = await tm.begin()

        task_vars.registry.set(None)
        task_vars.container.set(container)

        api = WikipediaAPI()
        folder_count = 0
        async for page_data in api.iter_pages():
            await self.import_folder(api, tm, txn, container, page_data)
            folder_count += 1
            if folder_count >= self.arguments.per_node:
github plone / guillotina / guillotina / api / content.py View on Github external
async def __call__(self):
        serializer = get_multi_adapter((self.context, self.request), IResourceSerializeToJson)
        include = omit = []
        if self.request.query.get("include"):
            include = self.request.query.get("include").split(",")
        if self.request.query.get("omit"):
            omit = self.request.query.get("omit").split(",")
        try:
            result = await serializer(include=include, omit=omit)
        except TypeError:
            result = await serializer()
        await notify(ObjectVisitedEvent(self.context))
        return result
github plone / guillotina / guillotina / factory / app.py View on Github external
# Make and initialize asgi app
    root.app = server_app
    server_app.root = root
    server_app.config = config
    server_app.settings = app_settings

    for k, v in _moved.items():
        # for b/w compatibility, convert these
        if k in app_settings:
            app_settings[v] = app_settings[k]
            del app_settings[k]

    optimize_settings(app_settings)

    await notify(ApplicationConfiguredEvent(server_app, loop))

    for key, dbconfig in list_or_dict_items(app_settings["databases"]):
        factory = get_utility(IDatabaseConfigurationFactory, name=dbconfig["storage"])
        root[key] = await factory(key, dbconfig, loop)
        await notify(DatabaseInitializedEvent(root[key]))

    for key, file_path in list_or_dict_items(app_settings["static"]):
        path = resolve_path(file_path).resolve()
        if not path.exists():
            raise Exception("Invalid static directory {}".format(file_path))
        if path.is_dir():
            root[key] = StaticDirectory(path)
        else:
            root[key] = StaticFile(path)

    for key, file_path in list_or_dict_items(app_settings["jsapps"]):
github plone / guillotina / guillotina / api / content.py View on Github external
result["local"]["prinrole"] = prinrole._bycol
    for obj in iter_parents(context):
        roleperm = IRolePermissionMap(obj, None)
        url = get_object_url(obj, request)
        if roleperm is not None and url is not None:
            prinperm = IPrincipalPermissionMap(obj)
            prinrole = IPrincipalRoleMap(obj)
            result["inherit"].append(
                {
                    "@id": url,
                    "roleperm": roleperm._bycol,
                    "prinperm": prinperm._bycol,
                    "prinrole": prinrole._bycol,
                }
            )
    await notify(ObjectPermissionsViewEvent(context))
    return result
github plone / guillotina / guillotina / api / content.py View on Github external
try:
            await deserializer(data, validate_all=True)
        except DeserializationError as e:
            return ErrorResponse(
                'DeserializationError',
                str(e),
                exc=e,
                status=400)

        # Local Roles assign owner as the creator user
        roleperm = IPrincipalRoleManager(obj)
        roleperm.assign_role_to_principal(
            'guillotina.Owner',
            user)

        await notify(ObjectAddedEvent(obj, self.context, obj.id, data=data))

        absolute_url = queryMultiAdapter((obj, self.request), IAbsoluteURL)

        headers = {
            'Access-Control-Expose-Headers': 'Location',
            'Location': absolute_url()
        }

        serializer = queryMultiAdapter(
            (obj, self.request),
            IResourceSerializeToJson
        )
        response = await serializer()
        return Response(response=response, headers=headers, status=201)
github plone / guillotina / guillotina / api / content.py View on Github external
async def __call__(self):
        content_id = self.context.id
        parent = self.context.__parent__
        await notify(BeforeObjectRemovedEvent(self.context, parent, content_id))
        self.context._p_jar.delete(self.context)
        await notify(ObjectRemovedEvent(self.context, parent, content_id))
github plone / guillotina / guillotina / content.py View on Github external
else:
        new_obj.__acl__ = context.__acl__

    for behavior in context.__behaviors__:
        new_obj.add_behavior(behavior)
    # need to copy annotation data as well...
    # load all annotations for context
    [b for b in await get_all_behaviors(context, load=True)]
    annotations_container = IAnnotations(new_obj)
    for anno_id, anno_data in context.__gannotations__.items():
        new_anno_data = AnnotationData()
        for key, value in anno_data.items():
            new_anno_data[key] = value
        await annotations_container.async_set(anno_id, new_anno_data)

    await notify(
        ObjectDuplicatedEvent(
            new_obj, context, destination_ob, new_id, payload={"id": new_id, "destination": destination}
        )
    )
    return new_obj
github plone / guillotina / guillotina / contrib / dbusers / subscribers.py View on Github external
async def on_user_created(user: User, event: ObjectAddedEvent) -> None:
    # Store only the hash of the password
    user.password = hash_password(user.password)

    # Give user ownership to his own folder object by default
    roleperm = IPrincipalRoleManager(user)
    roleperm.assign_role_to_principal("guillotina.Owner", user.id)

    await notify(NewUserAdded(user))
github plone / guillotina / guillotina / api / content.py View on Github external
changed = True
        func(prinperm['permission'], prinperm['principal'])

    for roleperm in data.get('roleperm') or []:
        setting = roleperm['setting']
        if setting not in PermissionMap['roleperm']:
            raise AttributeError('Invalid Type')
        manager = IRolePermissionManager(context)
        operation = PermissionMap['roleperm'][setting]
        func = getattr(manager, operation)
        changed = True
        func(roleperm['permission'], roleperm['role'])

    if changed:
        context._p_register()  # make sure data is saved
        await notify(ObjectPermissionsModifiedEvent(context, data))
github plone / guillotina / guillotina / security / utils.py View on Github external
for roleperm in data.get("roleperm") or []:
        if not isinstance(roleperm, dict):
            raise PreconditionFailed(context, "Invalid Type, must be list {}".format(roleperm))
        setting = roleperm["setting"]
        if setting not in PermissionMap["roleperm"]:
            raise PreconditionFailed(context, "Invalid Type")
        manager = IRolePermissionManager(context)
        operation = PermissionMap["roleperm"][setting]
        func = getattr(manager, operation)
        changed = True
        func(roleperm["permission"], roleperm["role"])

    if changed:
        context.register()  # make sure data is saved
        await notify(ObjectPermissionsModifiedEvent(context, data))