本文整理汇总了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
示例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
示例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
示例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
示例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
示例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)
示例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
示例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)
示例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
示例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))
示例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))
示例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)
示例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)
示例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)
示例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