本文整理汇总了Python中sqlalchemy.orm.util.class_mapper函数的典型用法代码示例。如果您正苦于以下问题:Python class_mapper函数的具体用法?Python class_mapper怎么用?Python class_mapper使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了class_mapper函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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
示例16: _apply_data
def _apply_data(self, invoice, converted):
changed = False
# Apply schema fields to the customer object
field_names = [ p.key for p in class_mapper(Invoice).iterate_properties ]
for field_name in field_names:
if field_name in converted.keys():
if getattr(invoice, field_name) != converted[field_name]:
setattr(invoice, field_name, converted[field_name])
changed = True
if invoice.due_date != invoice.date + datetime.timedelta(days=converted['payment_term']):
invoice.due_date = invoice.date + datetime.timedelta(days=converted['payment_term'])
changed = True
if converted['recurring_term'] and invoice.recurring_date != invoice.date + datetime.timedelta(days=converted['recurring_term']):
invoice.recurring_date = invoice.date + datetime.timedelta(days=converted['recurring_term'])
changed = True
# Apply data of the items subforms
session = DBSession()
item_map = {}
for item in invoice.items:
item_map[item.id] = item
for index, item_data in enumerate(converted['item_list']):
if item_data['item_id']:
item_id = item_data['item_id']
item = item_map[item_id]
del item_map[item_id]
else:
item = InvoiceItem()
item.invoice = invoice
session.add(item)
changed = True
# Apply schema fields to the invoice item object
field_names = [ p.key for p in class_mapper(InvoiceItem).iterate_properties ]
for field_name in field_names:
if field_name in item_data.keys():
if getattr(item, field_name) != item_data[field_name]:
setattr(item, field_name, item_data[field_name])
changed = True
if item.item_number != index:
item.item_number = index
changed = True
# Remove invoice items that have been removed in the form
for item in item_map.values():
invoice.items.remove(item)
changed = True
return changed
开发者ID:seantis,项目名称:seantisinvoice,代码行数:47,代码来源:invoice.py
示例17: get_columns
def get_columns(model):
columns = [p.key for p in class_mapper(model).iterate_properties
if isinstance(p, (ColumnProperty, SynonymProperty)) \
and not p.key.startswith('_')]
for parent in model.mro():
columns += [key for key, value in parent.__dict__.iteritems()
if isinstance(value, hybrid_property)]
return columns
开发者ID:coyotevz,项目名称:nbs,代码行数:8,代码来源:rest.py
示例18: add_class_properties_xsd
def add_class_properties_xsd(self, tb, cls):
""" Add the XSD for the class properties to the ``TreeBuilder``. And
call the user ``sequence_callback``. """
for p in class_mapper(cls).iterate_properties:
if isinstance(p, ColumnProperty):
self.add_column_property_xsd(tb, p)
if self.sequence_callback:
self.sequence_callback(tb, cls)
开发者ID:elemoine,项目名称:papyrus,代码行数:8,代码来源:xsd.py
示例19: form_defaults
def form_defaults(self):
defaults = {}
session = DBSession()
company = session.query(Company).first()
field_names = [ p.key for p in class_mapper(Company).iterate_properties ]
form_fields = [ field[0] for field in company_schema.attrs ]
for field_name in field_names:
if field_name in form_fields:
defaults[field_name] = getattr(company, field_name)
return defaults
开发者ID:seantis,项目名称:seantisinvoice,代码行数:11,代码来源:company.py
示例20: form_defaults
def form_defaults(self):
session = DBSession()
company = session.query(Company).first()
defaults = {
'currency' : u'CHF',
'payment_term' : 30,
'tax' : company.tax,
}
if "invoice" in self.request.matchdict:
invoice_id = self.request.matchdict['invoice']
invoice = session.query(Invoice).filter_by(id=invoice_id).first()
if invoice:
field_names = [ p.key for p in class_mapper(Invoice).iterate_properties ]
form_fields = [ field[0] for field in invoice_schema.attrs ]
for field_name in field_names:
if field_name in form_fields:
defaults[field_name] = getattr(invoice, field_name)
defaults['payment_term'] = (invoice.due_date - invoice.date).days
if invoice.recurring_date:
defaults['recurring_term'] = (invoice.recurring_date - invoice.date).days
else:
defaults['recurring_term'] = None
# Default values for the item subforms
defaults['item_list'] = []
# Make test happy
invoice.items.sort(key=lambda obj: obj.item_number)
for item in invoice.items:
item_defaults = {}
field_names = [ p.key for p in class_mapper(InvoiceItem).iterate_properties ]
form_fields = [ field[0] for field in invoice_item_schema.attrs ]
for field_name in field_names:
if field_name in form_fields:
item_defaults[field_name] = getattr(item, field_name)
item_defaults['item_id'] = item.id
defaults['item_list'].append(item_defaults)
return defaults
开发者ID:seantis,项目名称:seantisinvoice,代码行数:41,代码来源:invoice.py
注:本文中的sqlalchemy.orm.util.class_mapper函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论