Python sqlalchemy.inspection.inspect() Examples
The following are 30
code examples of sqlalchemy.inspection.inspect().
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.inspection
, or try the search function
.
Example #1
Source File: general.py From marvin with BSD 3-Clause "New" or "Revised" License | 7 votes |
def _db_row_to_dict(row, remove_columns=False): """Converts a DB object to a dictionary.""" from sqlalchemy.inspection import inspect as sa_inspect from sqlalchemy.ext.hybrid import hybrid_property row_dict = collections.OrderedDict() columns = row.__table__.columns.keys() mapper = sa_inspect(row.__class__) for key, item in mapper.all_orm_descriptors.items(): if isinstance(item, hybrid_property): columns.append(key) for col in columns: if remove_columns and col in remove_columns: continue row_dict[col] = getattr(row, col) return row_dict
Example #2
Source File: test_unitofwork.py From sqlalchemy with MIT License | 6 votes |
def test_pep435_custom_sort_key(self): s = Session() a = self.classes.T3(id=self.three, value=1) b = self.classes.T3(id=self.four, value=2) s.add_all([a, b]) s.commit() c = self.classes.T3(id=self.five, value=0) s.add(c) states = [o._sa_instance_state for o in [b, a, c]] eq_( _sort_states(inspect(self.classes.T3), states), # pending come first, then "four" < "three" [o._sa_instance_state for o in [c, b, a]], )
Example #3
Source File: schemas.py From CTFd with Apache License 2.0 | 6 votes |
def sqlalchemy_to_pydantic( db_model: Type, *, exclude: Container[str] = [] ) -> Type[BaseModel]: """ Mostly copied from https://github.com/tiangolo/pydantic-sqlalchemy """ mapper = inspect(db_model) fields = {} for attr in mapper.attrs: if isinstance(attr, ColumnProperty): if attr.columns: column = attr.columns[0] python_type = column.type.python_type name = attr.key if name in exclude: continue default = None if column.default is None and not column.nullable: default = ... fields[name] = (python_type, default) pydantic_model = create_model( db_model.__name__, **fields # type: ignore ) return pydantic_model
Example #4
Source File: connection_field.py From graphene-sqlalchemy-filter with MIT License | 6 votes |
def _get_model_pks(model) -> 'Tuple[str, ...]': """ Get primary key field name. Args: model: SQLAlchemy model. Returns: Field name. """ model_pk_fields: 'Tuple[str]' = tuple( ( cast(str, name) for name, c in inspection.inspect(model).columns.items() if c.primary_key ) ) return model_pk_fields
Example #5
Source File: forms.py From marvin with BSD 3-Clause "New" or "Revised" License | 6 votes |
def _loadParams(self, newclass): ''' Loads all parameters from wtforms into a dictionary with key, value = {'parameter_name': 'parent WTForm name'}. Ignores hidden attributes and the Meta class ''' model = newclass.Meta.model schema = model.__table__.schema tablename = model.__table__.name mapper = sa_inspect(model) for key, item in mapper.all_orm_descriptors.items(): if isinstance(item, (hybrid_property, hybrid_method)): key = key elif isinstance(item, InstrumentedAttribute): key = item.key else: continue lookupKeyName = schema + '.' + tablename + '.' + key self._param_form_lookup[lookupKeyName] = newclass self._paramtree[newclass.Meta.model.__name__][key]
Example #6
Source File: __init__.py From lore with MIT License | 5 votes |
def get(cls, *key): session = Session() filter = {str(k.name): v for k, v in dict(zip(inspect(cls).primary_key, key)).items()} instance = session.query(cls).filter_by(**filter).first() session.close() return instance
Example #7
Source File: test_persist.py From lang2program with Apache License 2.0 | 5 votes |
def test_correct_table(self, table_dict): correct_columns = ['name', 'age', 'json'] correct_keys = ['name', 'age'] names = lambda cols: [col.name for col in cols] table = table_dict.table assert names(table.columns) == correct_columns assert names(inspect(table).primary_key.columns) == correct_keys
Example #8
Source File: test_persist.py From lang2program with Apache License 2.0 | 5 votes |
def test_correct_table(self, table_dict): correct_columns = ['name', 'age', 'json'] correct_keys = ['name', 'age'] names = lambda cols: [col.name for col in cols] table = table_dict.table assert names(table.columns) == correct_columns assert names(inspect(table).primary_key.columns) == correct_keys
Example #9
Source File: alchemy.py From flask-rest-jsonapi with MIT License | 5 votes |
def get_object(self, view_kwargs, qs=None): """Retrieve an object through sqlalchemy :params dict view_kwargs: kwargs from the resource view :return DeclarativeMeta: an object from sqlalchemy """ self.before_get_object(view_kwargs) id_field = getattr(self, 'id_field', inspect(self.model).primary_key[0].key) try: filter_field = getattr(self.model, id_field) except Exception: raise Exception("{} has no attribute {}".format(self.model.__name__, id_field)) url_field = getattr(self, 'url_field', 'id') filter_value = view_kwargs[url_field] query = self.retrieve_object_query(view_kwargs, filter_field, filter_value) if qs is not None: query = self.eagerload_includes(query, qs) try: obj = query.one() except NoResultFound: obj = None self.after_get_object(obj, view_kwargs) return obj
Example #10
Source File: alchemy.py From flask-rest-jsonapi with MIT License | 5 votes |
def apply_nested_fields(self, data, obj): nested_fields_to_apply = [] nested_fields = get_nested_fields(self.resource.schema, model_field=True) for key, value in data.items(): if key in nested_fields: nested_field_inspection = inspect(getattr(obj.__class__, key)) if not isinstance(nested_field_inspection, QueryableAttribute): raise InvalidType("Unrecognized nested field type: not a queryable attribute.") if isinstance(nested_field_inspection.property, RelationshipProperty): nested_model = getattr(obj.__class__, key).property.mapper.class_ if isinstance(value, list): nested_objects = [] for identifier in value: nested_object = nested_model(**identifier) nested_objects.append(nested_object) nested_fields_to_apply.append({'field': key, 'value': nested_objects}) else: nested_fields_to_apply.append({'field': key, 'value': nested_model(**value)}) elif isinstance(nested_field_inspection.property, ColumnProperty): nested_fields_to_apply.append({'field': key, 'value': value}) else: raise InvalidType("Unrecognized nested field type: not a RelationshipProperty or ColumnProperty.") for nested_field in nested_fields_to_apply: setattr(obj, nested_field['field'], nested_field['value'])
Example #11
Source File: __init__.py From alchemyjsonschema with MIT License | 5 votes |
def __init__(self, model, includes=None, excludes=None, history=None): self.mapper = inspect(model).mapper self.includes = includes self.excludes = excludes self.history = history or [] if includes and excludes: if set(includes).intersection(excludes): raise InvalidStatus( "Conflict includes={}, exclude={}".format(includes, excludes) )
Example #12
Source File: dictify.py From alchemyjsonschema with MIT License | 5 votes |
def __call__(self, name): if not self.name_stack: self.name_stack.append(name) model = getattr(self.module, name) self.inspect_stack.append(inspect(model)) return model else: self.name_stack.append(name) prop = self.inspect_stack[-1].get_property(name) assert isinstance(prop, RelationshipProperty) mapper = prop.mapper model = mapper.class_ self.inspect_stack.append(mapper) return model
Example #13
Source File: dictify.py From alchemyjsonschema with MIT License | 5 votes |
def _get_primary_keys_from_object(ob): return tuple(sorted(col.name for col in inspect(ob).mapper.primary_key))
Example #14
Source File: helpers.py From planespotter with MIT License | 5 votes |
def is_mapped_class(cls): """Returns ``True`` if and only if the specified SQLAlchemy model class is a mapped class. """ try: sqlalchemy_inspect(cls) return True except: return False # This code was adapted from :meth:`elixir.entity.Entity.to_dict` and # http://stackoverflow.com/q/1958219/108197.
Example #15
Source File: __init__.py From lore with MIT License | 5 votes |
def last(cls, order_by=None, limit=1, **filters): if order_by is None: order_by = inspect(cls).primary_key if isinstance(order_by, list) or isinstance(order_by, tuple): order_by = desc(*order_by) else: order_by = desc(order_by) return cls.first(order_by=order_by, limit=limit, **filters)
Example #16
Source File: __init__.py From lore with MIT License | 5 votes |
def first(cls, order_by=None, limit=1, **filters): if order_by is None: order_by = inspect(cls).primary_key result = cls.all(order_by=order_by, limit=limit, **filters) if limit == 1: if len(result) == 0: result = None else: result = result[0] return result
Example #17
Source File: model.py From sandman2 with Apache License 2.0 | 5 votes |
def links(self): """Return a dictionary of links to related resources that should be included in the *Link* header of an HTTP response. :rtype: dict """ link_dict = {'self': self.resource_uri()} for relationship in inspect( # pylint: disable=maybe-no-member self.__class__).relationships: if 'collection' not in relationship.key: instance = getattr(self, relationship.key) if instance: link_dict[str(relationship.key)] = instance.resource_uri() return link_dict
Example #18
Source File: api.py From watcher with Apache License 2.0 | 5 votes |
def _get_relationships(model): return inspect(model).relationships
Example #19
Source File: api.py From watcher with Apache License 2.0 | 5 votes |
def _set_eager_options(model, query): relationships = inspect(model).relationships for relationship in relationships: if not relationship.uselist: # We have a One-to-X relationship query = query.options(joinedload(relationship.key)) return query
Example #20
Source File: orm.py From temboard with PostgreSQL License | 5 votes |
def from_dict(cls, dict_values, recurse=False): """ Build an instance of this model from a dictionary. Additional keys are discarded along the way. Args: dict_values (dict): a dictionary from which the instance should be built recurse (bool): if ``True``, also builds related instances. Else, only the base columns are included. """ mapper = inspect(cls) columns_values = { key: value for key, value in dict_values.items() if key in mapper.column_attrs } if recurse: for key, relationship_property in mapper.relationships.items(): target_cls = relationship_property.mapper.class_ value = dict_values.get(key) if isinstance(value, dict): columns_values[key] = target_cls.from_dict(value) elif isinstance(value, list): subvalues = columns_values.setdefault(key, []) for val in value: if isinstance(val, dict): subvalues.append(target_cls.from_dict(val)) else: subvalues.append(target_cls(val)) return cls(**columns_values)
Example #21
Source File: base.py From MultiAlchemy with MIT License | 5 votes |
def _join_to_left(self, *args, **kwargs): right = args[1 if SQLA_VERSION_8 else 2] super(TenantQuery, self)._join_to_left(*args, **kwargs) _process_from(inspection.inspect(right).selectable, self)
Example #22
Source File: extended_declarative_base.py From uszipcode-project with MIT License | 5 votes |
def _get_primary_key_names(cls): return tuple([col.name for col in inspect(cls).primary_key])
Example #23
Source File: audit_log.py From n6 with GNU Affero General Public License v3.0 | 5 votes |
def __eq__(self, other): # We base the equality test on model instances' state objects # to mimic the way model instances are compared to each other # in `sqlalchemy.orm.attributes.History.from_collection()`. # In particular, we make use of this test in the method # `_get_current_without_added()` (when removing from a list # some values that may be instances of this class). if isinstance(other, _ModelInstanceWrapper): self_state = inspect(self._model_instance) other_state = inspect(other._model_instance) assert (isinstance(self_state, InstanceState) and isinstance(other_state, InstanceState)) return self_state == other_state return False
Example #24
Source File: notification.py From zou with GNU Affero General Public License v3.0 | 5 votes |
def serialize(self, obj_type=None, relations=False): attrs = inspect(self).attrs.keys() obj_dict = { attr: serialize_value(getattr(self, attr)) for attr in attrs } obj_dict["notification_type"] = obj_dict["type"] obj_dict["type"] = obj_type or type(self).__name__ return obj_dict
Example #25
Source File: serializer.py From zou with GNU Affero General Public License v3.0 | 5 votes |
def serialize(self, obj_type=None, relations=False): attrs = inspect(self).attrs.keys() if relations: obj_dict = { attr: serialize_value(getattr(self, attr)) for attr in attrs } else: obj_dict = { attr: serialize_value(getattr(self, attr)) for attr in attrs if not self.is_join(attr) } obj_dict["type"] = obj_type or type(self).__name__ return obj_dict
Example #26
Source File: model_base.py From a10-neutron-lbaas with Apache License 2.0 | 5 votes |
def create(cls, **kwargs): instance = cls(**kwargs) # Populate all the unspecified columns with their defaults for key, column in inspect(cls).columns.items(): if key not in kwargs and column.default is not None: arg = column.default.arg column_default = arg if callable(arg) else lambda: arg setattr(instance, key, column_default(instance)) return instance
Example #27
Source File: model_base.py From a10-neutron-lbaas with Apache License 2.0 | 5 votes |
def delete(self, db_session=None): db = db_session or inspect(self).session db.delete(self)
Example #28
Source File: backends.py From flask-msearch with BSD 3-Clause "New" or "Revised" License | 5 votes |
def fields(self): model = self.index.model schema_fields = self._fields() primary_keys = [key.name for key in inspect(model).primary_key] schema = getattr(model, "__msearch_schema__", dict()) for field in self.index.searchable: if '.' in field: fields = field.split('.') field_attr = getattr( getattr(model, fields[0]).property.mapper.class_, fields[1]) else: field_attr = getattr(model, field) if field in schema: field_type = schema[field] if isinstance(field_type, str): schema_fields[field] = self.fields_map(field_type) else: schema_fields[field] = field_type continue if hasattr(field_attr, 'descriptor') and isinstance( field_attr.descriptor, hybrid_property): schema_fields[field] = self.fields_map("text") continue if field in primary_keys: schema_fields[field] = self.fields_map("primary") continue field_type = field_attr.property.columns[0].type schema_fields[field] = self.fields_map(field_type) return schema_fields
Example #29
Source File: model.py From gamification-engine with MIT License | 5 votes |
def __getattr__(cls, item): if item == "__table__": return inspect(cls).local_table raise AttributeError(item)
Example #30
Source File: __init__.py From AnyBlok with Mozilla Public License 2.0 | 5 votes |
def has_sqlalchemy_fields(base): for p in base.__dict__.keys(): attr = base.__dict__[p] if inspection.inspect(attr, raiseerr=False) is not None: return True return False