Python sqlalchemy.ext.associationproxy.ASSOCIATION_PROXY Examples

The following are 5 code examples of sqlalchemy.ext.associationproxy.ASSOCIATION_PROXY(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module sqlalchemy.ext.associationproxy , or try the search function .
Example #1
Source File: models_base.py    From cloudify-manager with Apache License 2.0 6 votes vote down vote up
def _get_orm_descriptors(cls):
        """Return a dictionary with all ORM descriptor names as keys, and
        their types (TEXT, DateTime, etc.) as values.

        """
        # The descriptor needs to be invoked once (using __get__) in order
        # to have access to its attributes (e.g. `remote_attr`)
        all_descs = {name: desc.__get__(None, cls)
                     for name, desc in inspect(cls).all_orm_descriptors.items()
                     if not name.startswith('_')}
        attrs_dict = dict()

        for name, desc in all_descs.items():
            extension_type = _get_extension_type(desc)
            if extension_type is ASSOCIATION_PROXY:
                # Association proxies must be followed to get their type
                while not desc.remote_attr.is_attribute:
                    desc = desc.remote_attr

                # Get the type of the remote attribute
                attrs_dict[name] = desc.remote_attr.expression.type
            elif extension_type is HYBRID_PROPERTY:
                attrs_dict[name] = desc.type

        return attrs_dict 
Example #2
Source File: __init__.py    From pyramid-jsonapi with GNU Affero General Public License v3.0 5 votes vote down vote up
def __init__(self, name, obj, view_class):
        self.name = name
        self.obj = obj
        self.view_class = view_class
        self.src_class = self.view_class.model
        if isinstance(obj, RelationshipProperty):
            self.direction = self.rel_direction
            self.tgt_class = self.rel_tgt_class
        elif obj.extension_type is ASSOCIATION_PROXY:
            self.direction = self.proxy_direction
            self.tgt_class = self.proxy_tgt_class 
Example #3
Source File: utils.py    From neutron-lib with Apache License 2.0 5 votes vote down vote up
def filter_non_model_columns(data, model):
    """Return the attributes from data which are model columns.

    :param data: The dict containing the data to filter.
    :param model: The model who's column names are used when filtering data.
    :returns: A new dict who's keys are columns in model or are association
        proxies of the model.
    """
    mapper = sqlalchemy.inspect(model)
    columns = set(c.name for c in mapper.columns)
    columns.update(d.value_attr for d in mapper.all_orm_descriptors
                   if d.extension_type is ASSOCIATION_PROXY)
    return dict((k, v) for (k, v)
                in data.items() if k in columns) 
Example #4
Source File: sql_base.py    From QCFractal with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _get_col_types(cls):

        # Must use private attributes so that they are not shared by subclasses
        if hasattr(cls, "__columns") and hasattr(cls, "__hybrids") and hasattr(cls, "__relationships"):
            return cls.__columns, cls.__hybrids, cls.__relationships

        mapper = inspect(cls)

        cls.__columns = []
        cls.__hybrids = []
        cls.__relationships = {}
        for k, v in mapper.relationships.items():
            cls.__relationships[k] = {}
            cls.__relationships[k]["join_class"] = v.argument
            cls.__relationships[k]["remote_side_column"] = list(v.remote_side)[0]

        for k, c in mapper.all_orm_descriptors.items():

            if k == "__mapper__":
                continue

            if c.extension_type == ASSOCIATION_PROXY:
                continue

            if c.extension_type == HYBRID_PROPERTY:
                cls.__hybrids.append(k)
            elif k not in mapper.relationships:
                cls.__columns.append(k)

        return cls.__columns, cls.__hybrids, cls.__relationships 
Example #5
Source File: database.py    From eNMS with GNU General Public License v3.0 4 votes vote down vote up
def configure_events(self):
        @event.listens_for(self.base, "mapper_configured", propagate=True)
        def model_inspection(mapper, model):
            name = model.__tablename__
            for col in inspect(model).columns:
                if not col.info.get("model_properties", True):
                    continue
                model_properties[name].append(col.key)
                if col.type == PickleType and isinstance(col.default.arg, list):
                    property_types[col.key] = "list"
                else:
                    column_type = {
                        Boolean: "bool",
                        Integer: "int",
                        Float: "float",
                        JSON: "dict",
                        PickleType: "dict",
                    }.get(type(col.type), "str")
                    if col.key not in property_types:
                        property_types[col.key] = column_type
            for descriptor in inspect(model).all_orm_descriptors:
                if descriptor.extension_type is ASSOCIATION_PROXY:
                    property = (
                        descriptor.info.get("name")
                        or f"{descriptor.target_collection}_{descriptor.value_attr}"
                    )
                    model_properties[name].append(property)
            if hasattr(model, "parent_type"):
                model_properties[name].extend(model_properties[model.parent_type])
            if "service" in name and name != "service":
                model_properties[name].extend(model_properties["service"])
            models.update({name: model, name.lower(): model})
            model_properties[name].extend(model.model_properties)
            model_properties[name] = list(set(model_properties[name]))
            for relation in mapper.relationships:
                if getattr(relation.mapper.class_, "private", False):
                    continue
                property = str(relation).split(".")[1]
                relationships[name][property] = {
                    "model": relation.mapper.class_.__tablename__,
                    "list": relation.uselist,
                }