本文整理汇总了Python中sqlalchemy.util.OrderedDict.values方法的典型用法代码示例。如果您正苦于以下问题:Python OrderedDict.values方法的具体用法?Python OrderedDict.values怎么用?Python OrderedDict.values使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类sqlalchemy.util.OrderedDict
的用法示例。
在下文中一共展示了OrderedDict.values方法的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: TableAnnotation
# 需要导入模块: from sqlalchemy.util import OrderedDict [as 别名]
# 或者: from sqlalchemy.util.OrderedDict import values [as 别名]
class TableAnnotation( object ):
"""
Annotations for Table objects, to annotate as needed, the notion
is that the annotation keys correspond to column, and values correspond
to application specific column metadata.
"""
_marker = object()
schema_invariants = ()
def __init__(self, table_name, columns=(), properties=(), schema_order=(), listing_columns=(), order_by=()):
self.table_name = table_name
self._options = {}
self._annot = OrderedDict()
for info in columns:
self._annot[ info['name'] ] = info
self.properties = properties
self.schema_order = schema_order
self.listing_columns = listing_columns
self.order_by = order_by
def setOption( self, name, value ):
self._options[ name ] = value
def getOption( self, name, default=None ):
return self._options.get( name, default )
def __call__( self, iface ):
return self
def __setitem__(self, name, value ):
self._annot[name] = value
def get( self, name, default=None ):
return self._annot.get( name, default )
def __getitem__(self, name):
return self.get( name )
def values( self ):
return self._annot.values()
def __contains__(self, name ):
return not self._marker == self.get( name, self._marker )
示例2: TableAnnotation
# 需要导入模块: from sqlalchemy.util import OrderedDict [as 别名]
# 或者: from sqlalchemy.util.OrderedDict import values [as 别名]
class TableAnnotation( object ):
#__slots__ = ("table_name", "_annot", "_options")
def __init__(self, table_name, columns=(), properties=(), schema_order=(), table_columns=(), order_by=()):
self.table_name = table_name
self._options = {}
self._annot = OrderedDict()
for info in columns:
self._annot[ info['name'] ] = info
self.properties = properties
self.schema_order = schema_order
self.table_columns = table_columns
self.order_by = order_by
def setOption( self, name, value ):
self._options[ name ] = value
def getOption( self, name, default=None ):
return self._options.get( name, default )
def __call__( self, context ):
return ModelAnnotation( context, self )
def __setitem__(self, name, value ):
self._annot[name] = value
def get( self, name, default=None ):
return self._annot.get( name, default )
def __getitem__(self, anme):
return self.get( name )
def values( self ):
return self._annot.values()
def __contains__(self, name ):
marker = object()
return not marker == self.get( name, marker )
示例3: FieldSet
# 需要导入模块: from sqlalchemy.util import OrderedDict [as 别名]
# 或者: from sqlalchemy.util.OrderedDict import values [as 别名]
class FieldSet(BaseFieldSet):
"""FieldSet aware of zope schema. See :class:`formalchemy.forms.FieldSet` for full api."""
__sa__ = False
_fields_mapping = {
schema.TextLine: fatypes.Unicode,
schema.Text: fatypes.Unicode,
schema.Int: fatypes.Integer,
schema.Bool: fatypes.Boolean,
schema.Float: fatypes.Float,
schema.Date: fatypes.Date,
schema.Datetime: fatypes.DateTime,
schema.Time: fatypes.Time,
schema.Choice: fatypes.Unicode,
schema.List: fatypes.List,
schema.Password: fatypes.Unicode,
}
def __init__(self, model, **kwargs):
BaseFieldSet.__init__(self, model, **kwargs)
self.iface = model
self.rebind(model)
self._fields = OrderedDict()
self._render_fields = OrderedDict()
self._bound_pk = None
for name, field in schema.getFieldsInOrder(self.iface):
klass = field.__class__
try:
t = self._fields_mapping[klass]
except KeyError:
raise NotImplementedError('%s is not mapped to a type' % klass)
else:
self.append(Field(name=name, type=t))
self._fields[name].label_text = field.title or name
if field.description:
self._fields[name].set(instructions=field.description)
if field.required:
self._fields[name].validators.append(validators.required)
if klass is schema.Password:
self._fields[name].set(renderer=fields.PasswordFieldRenderer)
if klass is schema.Text:
self._fields[name].set(renderer=fields.TextAreaFieldRenderer)
if klass is schema.List:
value_type = self.iface[name].value_type
if isinstance(value_type, schema.Choice):
self._fields[name].set(options=value_type, multiple=True)
else:
self._fields[name].set(multiple=True)
elif klass is schema.Choice:
self._fields[name].set(renderer=fields.SelectFieldRenderer,
options=self.iface[name])
def bind(self, model, session=None, data=None, request=None):
if not (model is not None or session or data):
raise Exception('must specify at least one of {model, session, data}')
# copy.copy causes a stacktrace on python 2.5.2/OSX + pylons. unable to reproduce w/ simpler sample.
mr = object.__new__(self.__class__)
mr.__dict__ = dict(self.__dict__)
# two steps so bind's error checking can work
mr.rebind(model, session, data)
mr._request = request
mr._fields = OrderedDict([(key, renderer.bind(mr)) for key, renderer in self._fields.items()])
if self._render_fields:
mr._render_fields = OrderedDict([(field.key, field) for field in
[field.bind(mr) for field in self._render_fields.values()]])
return mr
def gen_model(self, model=None, dict_like=False, **kwargs):
if model and self.iface.providedBy(model):
return model
factory = gen_model(self.iface, model, dict_like=dict_like)
model = factory(context=model, **kwargs)
return model
def rebind(self, model, session=None, data=None):
if model is not self.iface:
if model and not self.iface.providedBy(model):
if getattr(model, '__implemented__', None) is not None:
raise ValueError('%r does not provide %r' % (model, self.iface))
model = self.gen_model(model)
self.model = model
self._bound_pk = fields._pk(model)
if data is None:
self.data = None
elif hasattr(data, 'getall') and hasattr(data, 'getone'):
self.data = data
else:
try:
self.data = SimpleMultiDict(data)
except:
raise Exception('unsupported data object %s. currently only dicts and Paste multidicts are supported' % self.data)
示例4: ModelRenderer
# 需要导入模块: from sqlalchemy.util import OrderedDict [as 别名]
# 或者: from sqlalchemy.util.OrderedDict import values [as 别名]
class ModelRenderer(object):
"""
The `ModelRenderer` class is the superclass for all classes needing to deal
with `model` access and supporting rendering capabilities.
"""
prettify = staticmethod(prettify)
def __init__(self, model, session=None, data=None, prefix=None):
"""
- `model`:
a SQLAlchemy mapped class or instance. New object creation
should be done by passing the class, which will need a default
(no-parameter) constructor. After construction or binding of
the :class:`~formalchemy.forms.FieldSet`, the instantiated object will be available as
the `.model` attribute.
- `session=None`:
the session to use for queries (for relations). If `model` is associated
with a session, that will be used by default. (Objects mapped with a
`scoped_session
<http://www.sqlalchemy.org/docs/05/session.html#contextual-thread-local-sessions>`_
will always have a session. Other objects will
also have a session if they were loaded by a Query.)
- `data=None`:
dictionary-like object of user-submitted data to validate and/or
sync to the `model`. Scalar attributes should have a single
value in the dictionary; multi-valued relations should have a
list, even if there are zero or one values submitted. Currently,
pylons request.params() objects and plain dictionaries are known
to work.
- `prefix=None`:
the prefix to prepend to html name attributes. This is useful to avoid
field name conflicts when there are two fieldsets creating objects
from the same model in one html page. (This is not needed when
editing existing objects, since the object primary key is used as part
of the field name.)
Only the `model` parameter is required.
After binding, :class:`~formalchemy.forms.FieldSet`'s `model` attribute will always be an instance.
If you bound to a class, `FormAlchemy` will call its constructor with no
arguments to create an appropriate instance.
.. NOTE::
This instance will not be added to the current session, even if you are using `Session.mapper`.
All of these parameters may be overridden by the `bind` or `rebind`
methods. The `bind` method returns a new instance bound as specified,
while `rebind` modifies the current :class:`~formalchemy.forms.FieldSet` and has
no return value. (You may not `bind` to a different type of SQLAlchemy
model than the initial one -- if you initially bind to a `User`, you
must subsequently bind `User`'s to that :class:`~formalchemy.forms.FieldSet`.)
Typically, you will configure a :class:`~formalchemy.forms.FieldSet` once in
your common form library, then `bind` specific instances later for editing. (The
`bind` method is thread-safe; `rebind` is not.) Thus:
load stuff:
>>> from formalchemy.tests import FieldSet, User, session
now, in `library.py`
>>> fs = FieldSet(User)
>>> fs.configure(options=[]) # put all configuration stuff here
and in `controller.py`
>>> from library import fs
>>> user = session.query(User).first()
>>> fs2 = fs.bind(user)
>>> html = fs2.render()
The `render_fields` attribute is an OrderedDict of all the `Field`'s
that have been configured, keyed by name. The order of the fields
is the order in `include`, or the order they were declared
in the SQLAlchemy model class if no `include` is specified.
The `_fields` attribute is an OrderedDict of all the `Field`'s
the ModelRenderer knows about, keyed by name, in their
unconfigured state. You should not normally need to access
`_fields` directly.
(Note that although equivalent `Field`'s (fields referring to
the same attribute on the SQLAlchemy model) will equate with
the == operator, they are NOT necessarily the same `Field`
instance. Stick to referencing `Field`'s from their parent
`FieldSet` to always get the "right" instance.)
"""
self._fields = OrderedDict()
self._render_fields = OrderedDict()
self.model = self.session = None
self.prefix = prefix
if not model:
raise Exception('model parameter may not be None')
#.........这里部分代码省略.........
示例5: FieldSet
# 需要导入模块: from sqlalchemy.util import OrderedDict [as 别名]
# 或者: from sqlalchemy.util.OrderedDict import values [as 别名]
class FieldSet(DefaultRenderers):
"""
A `FieldSet` is bound to a SQLAlchemy mapped instance (or class, for
creating new instances) and can render a form for editing that instance,
perform validation, and sync the form data back to the bound instance.
`FieldSets` are responsible for generating HTML fields from a given
`model`.
You can derive your own subclasses from `FieldSet` to provide a customized
`render` and/or `configure`.
You can write `render` by manually sticking strings together if that's what you want,
but we recommend using a templating package for clarity and maintainability.
!FormAlchemy includes the Tempita templating package as formalchemy.tempita;
see http://pythonpaste.org/tempita/ for documentation.
`formalchemy.forms.template_text_tempita` is the default template used by `FieldSet.`
!FormAlchemy also includes a Mako version, `formalchemy.forms.template_text_mako`,
and will use that instead if Mako is available. The rendered HTML is identical
but (we suspect) Mako is faster.
Usage:
- `model`:
a SQLAlchemy mapped class or instance. New object creation
should be done by passing the class, which will need a default
(no-parameter) constructor. After construction or binding of
the :class:`~formalchemy.forms.FieldSet`, the instantiated object will be available as
the `.model` attribute.
- `session=None`:
the session to use for queries (for relations). If `model` is associated
with a session, that will be used by default. (Objects mapped with a
`scoped_session
<http://www.sqlalchemy.org/docs/05/session.html#contextual-thread-local-sessions>`_
will always have a session. Other objects will
also have a session if they were loaded by a Query.)
- `data=None`:
dictionary-like object of user-submitted data to validate and/or
sync to the `model`. Scalar attributes should have a single
value in the dictionary; multi-valued relations should have a
list, even if there are zero or one values submitted. Currently,
pylons request.params() objects and plain dictionaries are known
to work.
- `request=None`:
WebOb-like object that can be taken in place of `data`.
FormAlchemy will make sure it's a POST, and use its 'POST'
attribute as the data. Also, the request object will be
available to renderers as the `.request` attribute.
- `prefix=None`:
the prefix to prepend to html name attributes. This is useful to avoid
field name conflicts when there are two fieldsets creating objects
from the same model in one html page. (This is not needed when
editing existing objects, since the object primary key is used as part
of the field name.)
Only the `model` parameter is required.
After binding, :class:`~formalchemy.forms.FieldSet`'s `model` attribute will always be an instance.
If you bound to a class, `FormAlchemy` will call its constructor with no
arguments to create an appropriate instance.
.. NOTE::
This instance will not be added to the current session, even if you are using `Session.mapper`.
All of these parameters may be overridden by the `bind` or `rebind`
methods. The `bind` method returns a new instance bound as specified,
while `rebind` modifies the current :class:`~formalchemy.forms.FieldSet` and has
no return value. (You may not `bind` to a different type of SQLAlchemy
model than the initial one -- if you initially bind to a `User`, you
must subsequently bind `User`'s to that :class:`~formalchemy.forms.FieldSet`.)
Typically, you will configure a :class:`~formalchemy.forms.FieldSet` once in
your common form library, then `bind` specific instances later for editing. (The
`bind` method is thread-safe; `rebind` is not.) Thus:
load stuff:
>>> from formalchemy.tests import FieldSet, User, session
now, in `library.py`
>>> fs = FieldSet(User)
>>> fs.configure(options=[]) # put all configuration stuff here
and in `controller.py`
>>> from library import fs
>>> user = session.query(User).first()
>>> fs2 = fs.bind(user)
>>> html = fs2.render()
The `render_fields` attribute is an OrderedDict of all the `Field`'s
that have been configured, keyed by name. The order of the fields
#.........这里部分代码省略.........
示例6: ApplyBatchImpl
# 需要导入模块: from sqlalchemy.util import OrderedDict [as 别名]
# 或者: from sqlalchemy.util.OrderedDict import values [as 别名]
class ApplyBatchImpl(object):
def __init__(self, table, table_args, table_kwargs, reflected):
self.table = table # this is a Table object
self.table_args = table_args
self.table_kwargs = table_kwargs
self.temp_table_name = self._calc_temp_name(table.name)
self.new_table = None
self.column_transfers = OrderedDict(
(c.name, {"expr": c}) for c in self.table.c
)
self.reflected = reflected
self._grab_table_elements()
@classmethod
def _calc_temp_name(cls, tablename):
return ("_alembic_tmp_%s" % tablename)[0:50]
def _grab_table_elements(self):
schema = self.table.schema
self.columns = OrderedDict()
for c in self.table.c:
c_copy = c.copy(schema=schema)
c_copy.unique = c_copy.index = False
# ensure that the type object was copied,
# as we may need to modify it in-place
if isinstance(c.type, SchemaEventTarget):
assert c_copy.type is not c.type
self.columns[c.name] = c_copy
self.named_constraints = {}
self.unnamed_constraints = []
self.indexes = {}
self.new_indexes = {}
for const in self.table.constraints:
if _is_type_bound(const):
continue
elif self.reflected and isinstance(const, CheckConstraint):
# TODO: we are skipping reflected CheckConstraint because
# we have no way to determine _is_type_bound() for these.
pass
elif const.name:
self.named_constraints[const.name] = const
else:
self.unnamed_constraints.append(const)
for idx in self.table.indexes:
self.indexes[idx.name] = idx
for k in self.table.kwargs:
self.table_kwargs.setdefault(k, self.table.kwargs[k])
def _transfer_elements_to_new_table(self):
assert self.new_table is None, "Can only create new table once"
m = MetaData()
schema = self.table.schema
self.new_table = new_table = Table(
self.temp_table_name,
m,
*(list(self.columns.values()) + list(self.table_args)),
schema=schema,
**self.table_kwargs
)
for const in (
list(self.named_constraints.values()) + self.unnamed_constraints
):
const_columns = set(
[c.key for c in _columns_for_constraint(const)]
)
if not const_columns.issubset(self.column_transfers):
continue
if isinstance(const, ForeignKeyConstraint):
if _fk_is_self_referential(const):
# for self-referential constraint, refer to the
# *original* table name, and not _alembic_batch_temp.
# This is consistent with how we're handling
# FK constraints from other tables; we assume SQLite
# no foreign keys just keeps the names unchanged, so
# when we rename back, they match again.
const_copy = const.copy(
schema=schema, target_table=self.table
)
else:
# "target_table" for ForeignKeyConstraint.copy() is
# only used if the FK is detected as being
# self-referential, which we are handling above.
const_copy = const.copy(schema=schema)
else:
const_copy = const.copy(schema=schema, target_table=new_table)
if isinstance(const, ForeignKeyConstraint):
self._setup_referent(m, const)
new_table.append_constraint(const_copy)
def _gather_indexes_from_both_tables(self):
idx = []
idx.extend(self.indexes.values())
#.........这里部分代码省略.........
示例7: CospreadDataRecords
# 需要导入模块: from sqlalchemy.util import OrderedDict [as 别名]
# 或者: from sqlalchemy.util.OrderedDict import values [as 别名]
#.........这里部分代码省略.........
last_title = None
for col_index, row_val in enumerate(row):
if not row_val:
title = None
if last_title in self.column_spreading_titles:
title = "%s - %s" % (last_title, next_row[col_index])
else:
title = row_val.strip().replace(" ", " ")
last_title = title
if title in self.column_spreading_titles:
title = "%s - %s" % (title, next_row[col_index])
titles.append(title)
return (titles, row_index + 1)
row_index += 1
def create_title_mapping(self):
"""Creates a mapping between the spreadsheet\'s actual column
titles and the normalised versions.
Results in self.title_map and self.title_reverse_map which are
comprehensive for this spreadsheet.
"""
self.title_map = OrderedDict()
for title in self.titles:
for norm_title, regex in self.title_normaliser:
if regex.match(title):
self.title_map[title] = norm_title
break
else:
raise AssertionError("Did not recognise title: %r" % title)
self.title_reverse_map = dict((v, k) for k, v in self.title_map.iteritems())
# check all keys map both ways
unmatched_keys = set(self.title_map.keys()) - set(self.title_reverse_map.values())
if unmatched_keys:
msg = "Columns not identified by REs: %r" % (
set(self.title_map.keys()) - set(self.title_reverse_map.values())
)
msg += "\nColumns over identified by REs: %r" % (
set(self.title_reverse_map.keys()) - set(self.title_map.values())
)
raise AssertionError(msg)
@property
def records(self):
"""Returns package records.
* Collates packages with download_url in multiple rows in resources.
* Collapses 'Standard' / 'Other' column pairs into single value.
* Renames columns to standard names.
"""
current_record = None
package_identity_column = "Package name" if not self.generate_names else "Title"
self.create_title_mapping()
try:
def get_record_key(record_, standard_key):
alt_key = self.title_reverse_map.get(standard_key)
if alt_key and alt_key in record_:
return alt_key
else:
return standard_key
return record_[self.title_reverse_map[property]]
for record in super(CospreadDataRecords, self).records:
if (
current_record
示例8: ApplyBatchImpl
# 需要导入模块: from sqlalchemy.util import OrderedDict [as 别名]
# 或者: from sqlalchemy.util.OrderedDict import values [as 别名]
class ApplyBatchImpl(object):
def __init__(self, table, table_args, table_kwargs):
self.table = table # this is a Table object
self.table_args = table_args
self.table_kwargs = table_kwargs
self.new_table = None
self.column_transfers = OrderedDict(
(c.name, {'expr': c}) for c in self.table.c
)
self._grab_table_elements()
def _grab_table_elements(self):
schema = self.table.schema
self.columns = OrderedDict()
for c in self.table.c:
c_copy = c.copy(schema=schema)
c_copy.unique = c_copy.index = False
self.columns[c.name] = c_copy
self.named_constraints = {}
self.unnamed_constraints = []
self.indexes = {}
for const in self.table.constraints:
if _is_type_bound(const):
continue
if const.name:
self.named_constraints[const.name] = const
else:
self.unnamed_constraints.append(const)
for idx in self.table.indexes:
self.indexes[idx.name] = idx
def _transfer_elements_to_new_table(self):
assert self.new_table is None, "Can only create new table once"
m = MetaData()
schema = self.table.schema
self.new_table = new_table = Table(
'_alembic_batch_temp', m,
*(list(self.columns.values()) + list(self.table_args)),
schema=schema,
**self.table_kwargs)
for const in list(self.named_constraints.values()) + \
self.unnamed_constraints:
const_columns = set([
c.key for c in _columns_for_constraint(const)])
if not const_columns.issubset(self.column_transfers):
continue
const_copy = const.copy(schema=schema, target_table=new_table)
if isinstance(const, ForeignKeyConstraint):
self._setup_referent(m, const)
new_table.append_constraint(const_copy)
for index in self.indexes.values():
Index(index.name,
unique=index.unique,
*[new_table.c[col] for col in index.columns.keys()],
**index.kwargs)
def _setup_referent(self, metadata, constraint):
spec = constraint.elements[0]._get_colspec()
parts = spec.split(".")
tname = parts[-2]
if len(parts) == 3:
referent_schema = parts[0]
else:
referent_schema = None
if tname != '_alembic_batch_temp':
Table(
tname, metadata,
*[Column(n, sqltypes.NULLTYPE) for n in
[elem._get_colspec().split(".")[-1]
for elem in constraint.elements]],
schema=referent_schema)
def _create(self, op_impl):
self._transfer_elements_to_new_table()
op_impl.prep_table_for_batch(self.table)
op_impl.create_table(self.new_table)
try:
op_impl._exec(
self.new_table.insert(inline=True).from_select(
list(k for k, transfer in
self.column_transfers.items() if 'expr' in transfer),
select([
transfer['expr']
for transfer in self.column_transfers.values()
if 'expr' in transfer
])
)
)
op_impl.drop_table(self.table)
except:
op_impl.drop_table(self.new_table)
raise
#.........这里部分代码省略.........
示例9: ApplyBatchImpl
# 需要导入模块: from sqlalchemy.util import OrderedDict [as 别名]
# 或者: from sqlalchemy.util.OrderedDict import values [as 别名]
class ApplyBatchImpl(object):
def __init__(self, table, table_args, table_kwargs):
self.table = table # this is a Table object
self.table_args = table_args
self.table_kwargs = table_kwargs
self.new_table = None
self.column_transfers = OrderedDict(
(c.name, {'expr': c}) for c in self.table.c
)
self._grab_table_elements()
def _grab_table_elements(self):
schema = self.table.schema
self.columns = OrderedDict()
for c in self.table.c:
c_copy = c.copy(schema=schema)
c_copy.unique = c_copy.index = False
self.columns[c.name] = c_copy
self.named_constraints = {}
self.unnamed_constraints = []
self.indexes = {}
self.new_indexes = {}
for const in self.table.constraints:
if _is_type_bound(const):
continue
if const.name:
self.named_constraints[const.name] = const
else:
self.unnamed_constraints.append(const)
for idx in self.table.indexes:
self.indexes[idx.name] = idx
for k in self.table.kwargs:
self.table_kwargs.setdefault(k, self.table.kwargs[k])
def _transfer_elements_to_new_table(self):
assert self.new_table is None, "Can only create new table once"
m = MetaData()
schema = self.table.schema
self.new_table = new_table = Table(
'_alembic_batch_temp', m,
*(list(self.columns.values()) + list(self.table_args)),
schema=schema,
**self.table_kwargs)
for const in list(self.named_constraints.values()) + \
self.unnamed_constraints:
const_columns = set([
c.key for c in _columns_for_constraint(const)])
if not const_columns.issubset(self.column_transfers):
continue
if isinstance(const, ForeignKeyConstraint):
if _fk_is_self_referential(const):
# for self-referential constraint, refer to the
# *original* table name, and not _alembic_batch_temp.
# This is consistent with how we're handling
# FK constraints from other tables; we assume SQLite
# no foreign keys just keeps the names unchanged, so
# when we rename back, they match again.
const_copy = const.copy(
schema=schema, target_table=self.table)
else:
# "target_table" for ForeignKeyConstraint.copy() is
# only used if the FK is detected as being
# self-referential, which we are handling above.
const_copy = const.copy(schema=schema)
else:
const_copy = const.copy(schema=schema, target_table=new_table)
if isinstance(const, ForeignKeyConstraint):
self._setup_referent(m, const)
new_table.append_constraint(const_copy)
def _gather_indexes_from_both_tables(self):
idx = []
idx.extend(self.indexes.values())
for index in self.new_indexes.values():
idx.append(
Index(
index.name,
unique=index.unique,
*[self.new_table.c[col] for col in index.columns.keys()],
**index.kwargs)
)
return idx
def _setup_referent(self, metadata, constraint):
spec = constraint.elements[0]._get_colspec()
parts = spec.split(".")
tname = parts[-2]
if len(parts) == 3:
referent_schema = parts[0]
else:
referent_schema = None
#.........这里部分代码省略.........
示例10: ArchetypesSchemaModel
# 需要导入模块: from sqlalchemy.util import OrderedDict [as 别名]
# 或者: from sqlalchemy.util.OrderedDict import values [as 别名]
class ArchetypesSchemaModel( object ):
translator_factory = ArchetypesFieldTranslator
serializer_factory = ArchetypeSerializer
def __init__(self, engine=None):
self._tables = OrderedDict()
self._peer_factories = {}
self.engine = engine or ProxyEngine()
self.generateDefaults()
self.serializer = self.serializer_factory( self )
# rebind
self.ident_translate = self.translator_factory.ident_translate
self.saveObject = self.serializer.saveObject
self.deleteObject = self.serializer.deleteObject
def __getitem__(self,key):
return self._peer_factories.get( key )
def createTables(self):
for table in self._tables.values():
table.create()
def createIdentity(self):
return self._peer_factories[ self._identity ]()
def getIdentityKlass(self):
return self._peer_factories[ self._identity ]
def generateDefaults( self ):
self._identity = "object_identity"
object_identity = rdb.Table( self._identity,
self.engine,
rdb.Column( "uid", rdb.String(50), primary_key=True ),
rdb.Column( "id", rdb.String(60) ),
rdb.Column( "table_name", rdb.String(50) )
)
class ObjectIdentity( object ): pass
rdb.assign_mapper( ObjectIdentity, object_identity )
self._tables[ self._identity ] = object_identity
self._peer_factories[ self._identity ] = ObjectIdentity
def loadType( self, archetype_klass, context):
if archetype_klass.portal_type in self._tables:
return
# check if its a tool content type, if so ignore
if issubclass( archetype_klass, UniqueObject):
return
instance = archetype_klass('fake_instance')
instance._at_is_fake_instance = True
instance._is_fake_instance = True
wrapped = instance.__of__( context )
wrapped.initializeArchetype()
self._loadInstance( instance )
# just to be sure
instance.unindexObject()
def _loadInstance( self, instance ):
relation_tables = []
primary_columns = [ rdb.Column( "uid", rdb.String(50), primary_key=True ) ]
portal_type = instance.portal_type
table_name = self.ident_translate( portal_type )
field_translator = self.translator_factory( self, table_name )
print "Processing Type", portal_type
d = {}
for field in instance.Schema().fields():
# filter badness from fields with same speling but different captilization.
field_name = self.ident_translate( field.getName() )
if field_name in d:
continue
result = field_translator.visit( field )
if result is None:
continue
elif isinstance( result, rdb.Column):
primary_columns.append( result )
elif isinstance( result, rdb.Table ):
relation_tables.append( result )
else:
print "Unexpected", result
raise RuntimeError
d[field_name] = None
#.........这里部分代码省略.........
示例11: ModelClass
# 需要导入模块: from sqlalchemy.util import OrderedDict [as 别名]
# 或者: from sqlalchemy.util.OrderedDict import values [as 别名]
class ModelClass(Model):
parent_name = 'Base'
def __init__(self, table, association_tables, inflect_engine, detect_joined):
super(ModelClass, self).__init__(table)
self.name = self._tablename_to_classname(table.name, inflect_engine)
self.children = []
self.attributes = OrderedDict()
# Assign attribute names for columns
for column in table.columns:
self._add_attribute(column.name, column)
# Add many-to-one relationships
pk_column_names = set(col.name for col in table.primary_key.columns)
for constraint in sorted(table.constraints, key=_get_constraint_sort_key):
if isinstance(constraint, ForeignKeyConstraint):
target_cls = self._tablename_to_classname(constraint.elements[0].column.table.name, inflect_engine)
if detect_joined and self.parent_name == 'Base' and set(constraint.columns) == pk_column_names:
self.parent_name = target_cls
else:
relationship_ = ManyToOneRelationship(self.name, target_cls, constraint, inflect_engine)
self._add_attribute(relationship_.preferred_name, relationship_)
# Add many-to-many relationships
for association_table in association_tables:
fk_constraints = [c for c in association_table.constraints if isinstance(c, ForeignKeyConstraint)]
fk_constraints.sort(key=_get_constraint_sort_key)
target_cls = self._tablename_to_classname(fk_constraints[1].elements[0].column.table.name, inflect_engine)
relationship_ = ManyToManyRelationship(self.name, target_cls, association_table)
self._add_attribute(relationship_.preferred_name, relationship_)
@staticmethod
def _tablename_to_classname(tablename, inflect_engine):
camel_case_name = ''.join(part[:1].upper() + part[1:] for part in tablename.split('_'))
return inflect_engine.singular_noun(camel_case_name) or camel_case_name
@staticmethod
def _convert_to_valid_identifier(name):
assert name, 'Identifier cannot be empty'
if name[0].isdigit() or iskeyword(name):
name = '_' + name
return _re_invalid_identifier.sub('_', name)
def _add_attribute(self, attrname, value):
attrname = tempname = self._convert_to_valid_identifier(attrname)
counter = 1
while tempname in self.attributes:
tempname = attrname + str(counter)
counter += 1
self.attributes[tempname] = value
return tempname
def add_imports(self, collector, nosequences=False):
super(ModelClass, self).add_imports(collector, nosequences=nosequences)
if any(isinstance(value, Relationship) for value in self.attributes.values()):
collector.add_literal_import('sqlalchemy.orm', 'relationship')
for child in self.children:
child.add_imports(collector, nosequences=nosequences)