Exemple #1
0
def add_local_role(session: db.Session, obj: object, role_name: str, principal_id: PrincipalIdType):
    """Add new local role."""
    from briefy.common.db.models.local_role import LocalRole
    payload = dict(
        item_type=obj.__class__.__name__.lower(),
        item_id=obj.id,
        role_name=role_name,
        principal_id=principal_id
    )
    lr = LocalRole.create(payload)
    session.add(lr)
    obj.local_roles.append(lr)
    logger.debug('Added: {0}'.format(lr))
Exemple #2
0
    def add_nodes(self, base_includes: t.Sequence[str],
                  excludes: t.Sequence[str], overrides: dict):
        """Add nodes to the schema."""
        if set(excludes) & set(base_includes):
            raise ValueError('excludes and includes are mutually exclusive.')

        properties = sorted(self.inspector.attrs, key=_creation_order)
        # Explicitly add overrides in here
        properties = [item.key for item in properties]
        all_fields = properties + [o for o in overrides if o not in properties]
        includes = []
        if base_includes:
            for item in base_includes:
                prefixed = f'_{item}'
                if item in all_fields:
                    includes.append(item)
                elif prefixed in all_fields:
                    includes.append(prefixed)

        for name in includes or all_fields:
            prop = self.inspector.attrs.get(name, name)
            if name in excludes or (includes and name not in includes):
                logger.debug(f'Attribute {name} skipped imperatively')
                continue

            name_overrides_copy = overrides.get(name, {}).copy()

            if (isinstance(prop, ColumnProperty)
                    and isinstance(prop.columns[0], Column)):
                node = self.get_schema_from_column(prop, name_overrides_copy)
            elif isinstance(prop, RelationshipProperty):
                if prop.mapper.class_ in self.parents_ and name not in includes:
                    continue
                node = self.get_schema_from_relationship(
                    prop, name_overrides_copy)
            elif isinstance(prop, colander.SchemaNode):
                node = prop
            elif isinstance(prop, str) and name in overrides:
                name_overrides_copy['name'] = prop
                node = colander.SchemaNode(**name_overrides_copy)
            else:
                logger.debug(
                    f'Attribute {name} skipped due to not being '
                    'a ColumnProperty or RelationshipProperty', )
                continue

            if node is not None:
                self.add(node)
Exemple #3
0
 def refresh(self, obj):
     """Invalidate and refresh a given model object."""
     region = self.region()
     region.invalidate(obj)
     klass = obj.__class__
     klass_name = klass.__name__
     uid = obj.id
     log_kwargs = {
         'name': klass_name,
         'uid': uid
     }
     logger.debug('Invalidate model {name} : {uid}'.format(
         **log_kwargs
     ))
     if self._enable_refresh:
         thread = Thread(target=refresher, args=[obj], kwargs=log_kwargs)
         thread.start()
Exemple #4
0
 def login(self,
           username: str = config.API_USERNAME,
           password: str = config.API_PASSWORD) -> t.Tuple[str, dict]:
     """Use briefy.rolleiflex email login to get a valid token."""
     uri = config.LOGIN_ENDPOINT
     data = dict(username=username)
     if config.ENV == 'development' or 'internal' not in uri:
         data.update(password=password)
     logger.debug(
         f'Login on rolleiflex with username: {username} endpoint: {uri}')
     response = requests.post(uri, data=data, headers=self.headers())
     if response.status_code == 200:
         result = response.json()
         token = result.get('token')
         user = result.get('user')
         return token, user
     else:
         msg = response.text
         error = f'Login failed! payload: {data} endpoint: {uri} message: {msg}'
         logger.error(error)
         raise Exception(error)
Exemple #5
0
    def _relationship_config(name: str, key: str, imp: dict,
                             decl: dict) -> ConfigOrNone:
        """Process overrides.

        :param name: RelationshipProperty name.
        :param key: Category name. i.e.: children, includes, excludes, overrides.
        :param imp: Imperative configuration.
        :param decl: Declarative configuration.
        :return: Configuration.
        """
        config = None
        imperative_children = imp.pop(key, None)
        declarative_children = decl.pop(key, None)
        if imperative_children is not None:
            config = imperative_children
            logger.debug(
                f'Relationship {name}: {key} overridden imperatively.')
        elif declarative_children is not None:
            config = declarative_children
            logger.debug(
                f'Relationship {name}: {key} overridden via declarative.')
        return config
Exemple #6
0
    def get_schema_from_relationship(self, prop: RelationshipProperty,
                                     overrides: dict) -> SchemaNode:
        """Build and return a :class:`colander.SchemaNode` for a relationship.

        The mapping process will translate one-to-many and many-to-many
        relationships from SQLAlchemy into a ``Sequence`` of ``Mapping`` nodes
        in Colander, and translate one-to-one and many-to-one relationships
        into a ``Mapping`` node in Colander.  The related class involved in the
        relationship will be recursively mapped by ColanderAlchemy as part of
        this process, following the same mapping process.

        This method uses information stored in the relationship within
        the ``info`` that was passed to the relationship on creation.
        This means that ``Colander`` options can be specified
        declaratively in ``SQLAlchemy`` models using the ``info``
        argument that you can pass to
        :meth:`sqlalchemy.orm.relationship`.

        For all relationships, the settings will only be applied to the outer
        Sequence or Mapping. To customise the inner schema node, create the
        attribute ``__colanderalchemy_config__`` on the related model with a
        dict-like structure corresponding to the Colander options that should
        be customised.

        Arguments/Keywords

        :param prop: RelationshipProperty
        :param overrides: Dictionary with attributes to be overriden.
        :return: SchemaNode instance.
        """
        # The name of the SchemaNode is the ColumnProperty key.
        name = self._change_name(prop)
        kwargs = {'name': name}
        decl_overrides = prop.info.get(self.sqla_info_key, {}).copy()
        self.declarative_overrides[name] = decl_overrides.copy()
        class_ = prop.mapper.class_
        if decl_overrides.pop('exclude', False):
            logger.debug(
                f'Relationship {name} skipped due to declarative overrides')
            return None

        for key in ['name', 'typ']:
            self.check_overrides(name, key, {}, decl_overrides, overrides)

        children = self._relationship_config(name, 'children', overrides,
                                             decl_overrides)
        includes = self._relationship_config(name, 'includes', overrides,
                                             decl_overrides)
        excludes = self._relationship_config(name, 'excludes', overrides,
                                             decl_overrides)
        rel_overrides = self._relationship_config(name, 'overrides', overrides,
                                                  decl_overrides)

        # Add default values for missing parameters.
        missing = []
        if prop.innerjoin:
            # Inner joined relationships imply it is mandatory
            missing = required

        kwargs['missing'] = missing

        kwargs.update(decl_overrides)
        kwargs.update(overrides)

        if children is not None:
            node_type = Mapping()
            if prop.uselist:
                # xToMany relationships.
                node_type = Sequence()
            return SchemaNode(node_type, *children, **kwargs)

        node = BriefySchemaNode(class_,
                                name=name,
                                includes=includes,
                                excludes=excludes,
                                overrides=rel_overrides,
                                missing=missing,
                                parents_=self.parents_ + [self.class_])

        if prop.uselist:
            node = SchemaNode(Sequence(), node, **kwargs)

        node.name = name
        return node
Exemple #7
0
def del_local_role(session: db.Session, obj: ItemType, lr: LocalRoleType):
    """Delete existing local role."""
    obj.local_roles.remove(lr)
    session.delete(lr)
    logger.debug('Deleted: {0}'.format(lr))
Exemple #8
0
 def set(self, key, value):
     """Proxy to debug when setting a cache value."""
     logger.debug('Starting setting cache key: %s' % key)
     self.proxied.set(key, value)
     logger.debug('Finish setting cache key: %s' % key)