当前位置: 首页>>代码示例>>Python>>正文


Python util.class_mapper函数代码示例

本文整理汇总了Python中sqlalchemy.orm.util.class_mapper函数的典型用法代码示例。如果您正苦于以下问题:Python class_mapper函数的具体用法?Python class_mapper怎么用?Python class_mapper使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了class_mapper函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: _is_sql_wrapper

def _is_sql_wrapper(instance):
    """Determines if instance is a SQLAlchemy wrapper (ORM instance)"""
    try:
        class_mapper(instance.__class__)
        return True
    except:
        return False
开发者ID:ivan-c,项目名称:true_nth_usa_portal,代码行数:7,代码来源:lazy.py

示例2: form_defaults

 def form_defaults(self):
     
     defaults = {}
     if "customer" in self.request.matchdict:
         customer_id = self.request.matchdict['customer']
         session = DBSession()
         customer = session.query(Customer).filter_by(id=customer_id).first()
         if customer:
             field_names = [ p.key for p in class_mapper(Customer).iterate_properties ]
             form_fields = [ field[0] for field in customer_schema.attrs ]
             for field_name in field_names:
                 if field_name in form_fields:
                     defaults[field_name] = getattr(customer, field_name)
                 
             # Default values for the contact subforms
             defaults['contact_list'] = []
             for contact in customer.contacts:
                 contact_defaults = {}
                 field_names = [ p.key for p in class_mapper(CustomerContact).iterate_properties ]
                 form_fields = [ field[0] for field in customer_contact_schmema.attrs ]
                 for field_name in field_names:
                     if field_name in form_fields:
                         contact_defaults[field_name] = getattr(contact, field_name)
                 contact_defaults['contact_id'] = contact.id
                 defaults['contact_list'].append(contact_defaults)
     
     return defaults
开发者ID:seantis,项目名称:seantisinvoice,代码行数:27,代码来源:customer.py

示例3: try_mapper

def try_mapper(module):
    for attr in dir(module):
        if attr[0] == '_': continue
        try:
            cls = getattr(module, attr)
            class_mapper(cls)
        except Exception as ex:
            if isinstance(ex, sqlalchemy.exc.InvalidRequestError):
                if ex.message.startswith("One or more mappers failed to initialize"):
                    return ex.message
    return None
开发者ID:lukasjuhrich,项目名称:pycroft,代码行数:11,代码来源:test_schema.py

示例4: is_sqlalchemy_model

def is_sqlalchemy_model(instance):
    """Return True if instance is an SQLAlchemy model instance."""
    from sqlalchemy.orm.util import class_mapper
    from sqlalchemy.orm.exc import UnmappedClassError

    try:
        class_mapper(instance.__class__)

    except UnmappedClassError:
        return False

    else:
        return True
开发者ID:kooba,项目名称:charlatan,代码行数:13,代码来源:utils.py

示例5: __read__

    def __read__(self):
        id = None
        geom = None
        bbox = None
        properties = {}
        for p in class_mapper(self.__class__).iterate_properties:
            if isinstance(p, ColumnProperty):
                if len(p.columns) != 1:  # pragma: no cover
                    raise NotImplementedError
                col = p.columns[0]
                val = getattr(self, p.key)
                if col.primary_key:
                    id = val
                elif (isinstance(col.type, GeometryChsdi) and
                      col.name == self.geometry_column_to_return().name):
                    if hasattr(self, '_shape') and \
                            len(self._shape) < MAX_FEATURE_GEOMETRY_SIZE:
                        geom = self._shape
                    elif val is not None and \
                            len(val.data) < MAX_FEATURE_GEOMETRY_SIZE:
                        geom = to_shape(val)
                    try:
                        bbox = geom.bounds
                    except:
                        pass
                elif (not col.foreign_keys and
                      not isinstance(col.type, GeometryChsdi)):
                    properties[p.key] = val
        properties = self.insert_label(properties)

        return id, geom, properties, bbox
开发者ID:geoadmin,项目名称:mf-chsdi3,代码行数:31,代码来源:__init__.py

示例6: __read__

    def __read__(self):
        id = None
        geom = None
        properties = {}
        for p in class_mapper(self.__class__).iterate_properties:
            if isinstance(p, ColumnProperty):
                if len(p.columns) != 1:  # pragma: no cover
                    raise NotImplementedError
                col = p.columns[0]
                val = getattr(self, p.key)
                if col.primary_key:
                    id = val
                elif isinstance(col.type, Geometry) and col.name == self.geometry_column_to_return().name:
                    if hasattr(self, '_shape'):
                        geom = self._shape
                    elif val is not None:
                        if len(val.data) > 1000000:
                            raise HTTPBandwidtLimited('Feature ID %s: is too large' % self.id)
                        geom = to_shape(val)
                elif not col.foreign_keys and not isinstance(col.type, Geometry):
                    properties[p.key] = val

        if self.__add_properties__:
            for k in self.__add_properties__:
                properties[k] = getattr(self, k)

        properties = self.insertLabel(properties)
        return geojson.Feature(id=id, geometry=geom, properties=properties)
开发者ID:cype,项目名称:mf-chsdi3,代码行数:28,代码来源:__init__.py

示例7: get_foreign_key_columns

def get_foreign_key_columns(clazz):
    '''Given a schema class, return {class column: foreign key class column}'''
    fk_cols = {}
    for column in class_mapper(clazz).columns:
        if column.foreign_keys:
            fk_cols[column] = next(iter(column.foreign_keys)).column
    return fk_cols
开发者ID:insight-unlp,项目名称:domainmodeller,代码行数:7,代码来源:schema.py

示例8: _handleClass

    def _handleClass(self, classTag):
        fqCname=classTag.getAttribute('name')
        rc=self._classFromName(fqCname)
        if rc in self._classes:
            raise ValueError("Invalid report configuration '%s': Each class tag must have a unique value. '%s' found more than once" % (self._rptID, fqCname))

        isOuter=classTag.getAttribute('outerjoin')
        if isOuter=='True':
            isOuter=True
        else:
            isOuter=False
        self._outerjoins[rc]=isOuter

        # Can explicitly set what to join on.  Needed when one table has two foreign key columns to the same
        # parent (or child) table.
        onclause = classTag.getAttribute('onclause')
        if onclause:
            try:
                (fqCname, propName) = onclause.rsplit('.', 1)
                joincl = self._classFromName(fqCname)
                joinCol = getattr(joincl, propName)
                self._onclause[rc]=joinCol
            except:
                raise ValueError("Invalid report configuration '%s' : onclause '%s' attribute must point to a property in another ORM class" % (self._rptID, onclause))

        # Get the set of unique attributes for this class, so that we
        # can keep track of which items in the UI should be unique
        uniqueAttributes=set()
        try:
            m=class_mapper(rc)
            for i in m.tables[0].indexes:
                if i.unique:
                    if len(i.columns) == 1:
                        attr=i.columns[0].name
                        uniqueAttributes.add(attr)
        except UnmappedClassError:
            pass

        # Build configuration for each column
        columnTags=classTag.getElementsByTagName('column')
        for columnTag in columnTags:
            column=self._handleCol(columnTag)
            column.modelClass=rc

            # Column id must be unique
            idValue=column.id
            if idValue in self._columns:
                raise ValueError("Invalid report configuration '%s': Each column tag must have a 'id' value.  '%s' found more than once" % (self._rptID, idValue))
            
            # Check if this column is associated with a db column
            if column.dbColId:
                if column.dbColId in uniqueAttributes:
                    column.unique=True
                dbCol=getattr(rc, column.dbColId, None)
                column.dbCol=dbCol
                self._dbcols[dbCol]=column

            self._columns[idValue]=column
            
        self._classes.append(rc)
开发者ID:aytsai,项目名称:ricebowl,代码行数:60,代码来源:report.py

示例9: __read__

    def __read__(self):
        id = None
        geom = None
        properties = {}
        for p in class_mapper(self.__class__).iterate_properties:
            if isinstance(p, ColumnProperty):
                if len(p.columns) != 1:  # pragma: no cover
                    raise NotImplementedError
                col = p.columns[0]
                val = getattr(self, p.key)
                if col.primary_key:
                    id = val
                elif (isinstance(col.type, GeometryChsdi) and
                      col.name == self.geometry_column_to_return().name):
                    if hasattr(self, '_shape'):
                        geom = self._shape
                    elif val is not None:
                        if len(val.data) > 1000000:
                            raise HTTPBandwidthLimited(
                                'Feature ID %s: is too large' % self.id)
                        geom = to_shape(val)
                elif (not col.foreign_keys and
                      not isinstance(col.type, GeometryChsdi)):
                    properties[p.key] = val
        properties = self.insert_label(properties)
        bbox = None
        try:
            bbox = geom.bounds
        except:
            pass

        return id, geom, properties, bbox
开发者ID:ioda-net,项目名称:mf-chsdi3,代码行数:32,代码来源:__init__.py

示例10: __update__

    def __update__(self, feature):
        """
        Called by the protocol on object update.

        Arguments:

        * ``feature`` The GeoJSON feature as received from the client.
        """
        for p in class_mapper(self.__class__).iterate_properties:
            if not isinstance(p, ColumnProperty):
                continue
            col = p.columns[0]
            if isinstance(col.type, Geometry):
                geom = feature.geometry
                if geom and not isinstance(geom, geojson.geometry.Default):
                    srid = col.type.srid
                    shape = asShape(geom)
                    setattr(self, p.key, from_shape(shape, srid=srid))
                    self._shape = shape
            elif not col.primary_key:
                if p.key in feature.properties:
                    setattr(self, p.key, feature.properties[p.key])

        if self.__add_properties__:
            for k in self.__add_properties__:
                setattr(self, k, feature.properties.get(k))
开发者ID:elemoine,项目名称:papyrus,代码行数:26,代码来源:geo_interface.py

示例11: meta_competence_edit_view

def meta_competence_edit_view(context, request):
    
    if IMetaCompetence.providedBy(context):
        add_form = False
        meta_competence = context
        context = meta_competence.__parent__
    else:
        meta_competence = MetaCompetence()
        add_form = True
    
    errors = {}
    defaults = {}
    
    if 'form.submitted' in request.POST:
        try:
            # FormEncode validation
            defaults = dict(request.POST)
            form_result = meta_competence_schema.to_python(request.POST)
        except formencode.validators.Invalid, why:
            errors=why.error_dict
        else:
            # Apply schema fields to the project object
            field_names = [ p.key for p in class_mapper(MetaCompetence).iterate_properties ]
            changed = False
            for field_name in field_names:
                if field_name in form_result.keys():
                    if form_result[field_name] != getattr(meta_competence, field_name):
                        setattr(meta_competence, field_name, form_result[field_name])
                        changed = True
            # Add onjective if this is the add form
            if add_form:
                session = DBSession()
                session.add(meta_competence) 
            return HTTPFound(location = model_url(context, request))
开发者ID:FvD,项目名称:cobal.eportfolio,代码行数:34,代码来源:meta_competence.py

示例12: __geo_interface__

    def __geo_interface__(self):
        """ Objects implement the Python Geo Interface, making them
        candidates to serialization with the ``geojson`` module, or
        Papyrus' GeoJSON renderer.
        """
        id = None
        geom = None
        properties = {}
        
        if hasattr(self, '_shape'):
            geom = self._shape

        for p in class_mapper(self.__class__).iterate_properties:
            if not isinstance(p, ColumnProperty):
                continue
            col = p.columns[0]
            val = getattr(self, p.key)
            if col.primary_key:
                id = val
            elif isinstance(col.type, Geometry):
                if not geom:
                    geom = wkb.loads(str(val.geom_wkb))
            else:
                properties[p.key] = val

        return geojson.Feature(id=id, geometry=geom, properties=properties)
开发者ID:GunioRobot,项目名称:papyrus,代码行数:26,代码来源:geo_interface.py

示例13: __read__

    def __read__(self):
        id = None
        geom = None
        properties = {}

        for p in class_mapper(self.__class__).iterate_properties:
            if isinstance(p, ColumnProperty):
                if len(p.columns) != 1:  # pragma: no cover
                    raise NotImplementedError
                col = p.columns[0]
                val = getattr(self, p.key)
                if col.primary_key:
                    id = val
                elif isinstance(col.type, Geometry) and col.name == self.geometry_column_to_return().name:
                    if hasattr(self, '_shape'):
                        geom = self._shape
                    else:
                        geom = wkb.loads(str(val.geom_wkb))
                elif not col.foreign_keys and not isinstance(col.type, Geometry):
                    properties[p.key] = val

        if self.__add_properties__:
            for k in self.__add_properties__:
                properties[k] = getattr(self, k)

        return geojson.Feature(id=id, geometry=geom, properties=properties)
开发者ID:justb4,项目名称:mf-chsdi3,代码行数:26,代码来源:__init__.py

示例14: __read__

    def __read__(self):
        """
        Called by :py:attr:`.__geo_interface__`.
        """
        id = None
        geom = None
        properties = {}

        for p in class_mapper(self.__class__).iterate_properties:
            if isinstance(p, ColumnProperty):
                if len(p.columns) != 1:  # pragma: no cover
                    raise NotImplementedError
                col = p.columns[0]
                val = getattr(self, p.key)
                if col.primary_key:
                    id = val
                elif isinstance(col.type, Geometry):
                    if hasattr(self, "_shape"):
                        geom = self._shape
                    elif val is not None:
                        geom = to_shape(val)
                elif not col.foreign_keys:
                    properties[p.key] = val

        if self.__add_properties__:
            for k in self.__add_properties__:
                properties[k] = getattr(self, k)

        return geojson.Feature(id=id, geometry=geom, properties=properties)
开发者ID:elemoine,项目名称:papyrus,代码行数:29,代码来源:geo_interface.py

示例15: __init__

    def __init__(self, session, mapped_class, children=None, attr_list=None):
        self.session = session
        self.mapped_class = mapped_class
        self.attr_list = attr_list

        self.columns = []
        self.relationships = {}
        self.id = None

        for p in class_mapper(mapped_class).iterate_properties:
            if isinstance(p, ColumnProperty):
                if len(p.columns) != 1:
                    raise NotImplementedError
                col = p.columns[0]
                if col.primary_key:
                    self.id = p.key
                elif not col.foreign_keys and \
                        attr_list is None or p.key in attr_list:
                    self.columns.append(p.key)
            elif children is not None and \
                    isinstance(p, RelationshipProperty) and \
                    p.key in children.keys():
                rel = children[p.key]
                if "rest" not in rel or not isinstance(rel["rest"], REST):
                    raise HTTPBadRequest(
                        "Missing REST object for relationship %s" % p.key
                    )
                self.relationships[p.key] = rel
开发者ID:sbrunner,项目名称:c2c.sqlalchemy.rest,代码行数:28,代码来源:__init__.py


注:本文中的sqlalchemy.orm.util.class_mapper函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。