本文整理汇总了Python中sqlalchemy.util.OrderedDict.items方法的典型用法代码示例。如果您正苦于以下问题:Python OrderedDict.items方法的具体用法?Python OrderedDict.items怎么用?Python OrderedDict.items使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类sqlalchemy.util.OrderedDict
的用法示例。
在下文中一共展示了OrderedDict.items方法的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: Relationship
# 需要导入模块: from sqlalchemy.util import OrderedDict [as 别名]
# 或者: from sqlalchemy.util.OrderedDict import items [as 别名]
class Relationship(object):
def __init__(self, source_cls, target_cls):
super(Relationship, self).__init__()
self.source_cls = source_cls
self.target_cls = target_cls
self.kwargs = OrderedDict()
@property
def suggested_names(self):
yield self.preferred_name if not iskeyword(self.preferred_name) else self.preferred_name + '_'
iteration = 0
while True:
iteration += 1
yield self.preferred_name + str(iteration)
def render(self):
text = 'relationship('
args = [repr(self.target_cls)]
if 'secondaryjoin' in self.kwargs:
text += '\n '
delimiter, end = ',\n ', '\n )'
else:
delimiter, end = ', ', ')'
args.extend([key + '=' + value for key, value in list(self.kwargs.items())])
return text + delimiter.join(args) + end
示例2: Relationship
# 需要导入模块: from sqlalchemy.util import OrderedDict [as 别名]
# 或者: from sqlalchemy.util.OrderedDict import items [as 别名]
class Relationship(object):
def __init__(self, source_cls, target_cls):
super(Relationship, self).__init__()
self.source_cls = source_cls
self.target_cls = target_cls
self.kwargs = OrderedDict()
def render(self):
text = 'relationship('
args = [repr(self.target_cls)]
if 'secondaryjoin' in self.kwargs:
text += '\n '
delimiter, end = ',\n ', '\n )'
else:
delimiter, end = ', ', ')'
args.extend([key + '=' + value for key, value in self.kwargs.items()])
return text + delimiter.join(args) + end
示例3: FieldSet
# 需要导入模块: from sqlalchemy.util import OrderedDict [as 别名]
# 或者: from sqlalchemy.util.OrderedDict import items [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: test_1_row_2_package
# 需要导入模块: from sqlalchemy.util import OrderedDict [as 别名]
# 或者: from sqlalchemy.util.OrderedDict import items [as 别名]
def test_1_row_2_package(self):
row_dict = OrderedDict([
(u'Dataset Ref#', u'BIS-000002'),
(u'Dataset Status', u'Proposed'),
(u'Agency', u'Higher Education Statistics Agency'),
(u'Primary Contact', u'[email protected]'),
(u'Secondary Contact', None),
(u'Title', u'Higher Education Statistics: All HE students by level of study, mode of study, subject of study, domicile and gender 2007/08'),
(u'Abstract', u'This dataset provides the 2007/08 higher education statistics for all students by level of study, mode of study, subject of study, domicile and gender'),
(u'Date Released', 2008),
(u'Date Updated', 2008),
(u'Update Frequency', u'Never'),
(u'Tags', u'hesa higher-education-statistics 2007-2008'),
(u'Department', u'Department for Business, Innovation & Skills'),
(u'Wiki', u'-'),
(u'Identifier', u'higher-education-statistics-all-he-students-by-level-of-study-mode-of-study-subject-of-study-meeeeeeeeeeeeeeeeeeeeeeeeeeeega-long-name-2007-2008'),
(u'Licence', u'Higher Education Statistcs Agency Copyright with data.gov.uk rights'),
(u'Version', u'-'),
(u'Geographic Coverage', u'United Kingdom (England, Scotland, Wales, Northern Ireland)'),
(u'Geographic Granularity', u'national'),
(u'Temporal Granularity', u'years'),
(u'Precision', u'integer to the nearest 5'),
(u'Taxonomy url', u'-'),
(u'Temporal Coverage From', datetime.date(2007, 8, 1)),
(u'Temporal Coverage To', datetime.date(2008, 7, 31)),
(u'National Statistic', u'no'),
(u'Categories', u'-'),
(u'Contact information', u'Higher Education Statistics Agency (HESA)\n+44 (0) 1242 211133\[email protected]'),
(u'Data File', 1),
(u'Reference Material', 2),
(u'Information', 0),
(u'Full Description', 0),
(u'Unknown', 0),
(u'Total', 3)
])
expected_pkg_dict = OrderedDict([
('name', u'hesa-all-he-students-by-level-of-study-mode-of-study-subject-of-study-meeeeeeeeeeeeee-2007-2008'),
('title', u'Higher Education Statistics: All HE students by level of study, mode of study, subject of study, domicile and gender 2007/08'),
('version', u'-'),
('url', None),
('author', u'Higher Education Statistics Agency (HESA)'),
('author_email', u'[email protected]'),
('maintainer', u''),
('maintainer_email', u''),
('notes', u'This dataset provides the 2007/08 higher education statistics for all students by level of study, mode of study, subject of study, domicile and gender'),
('license_id', u'hesa-withrights'),
('tags', [u'2007-2008', u'education', u'hesa', \
u'higher-education', u'higher-education-statistics']),
('groups', ['ukgov']),
('resources', [OrderedDict([
('url', 'http://www.hesa.ac.uk/dox/dataTables/studentsAndQualifiers/download/subject0708.xls?v=1.0'),
('format', 'XLS'),
('description', 'Data File - XLS Format'),
]),
OrderedDict([
('url', 'http://www.hesa.ac.uk/index.php/component/option,com_datatables/task,show_file/defs,1/Itemid,121/catdex,3/disp,/dld,subject0708.xls/yrStr,2007+to+2008/dfile,studefs0708.htm/area,subject/mx,0/'),
('format', 'HTML'),
('description', 'Reference Material - Data File Definition'),
]),
OrderedDict([
('url', 'http://www.hesa.ac.uk/index.php/component/option,com_datatables/task,show_file/defs,2/Itemid,121/catdex,3/disp,/dld,subject0708.xls/yrStr,2007+to+2008/dfile,notes0708.htm/area,subject/mx,0/'),
('format', 'HTML'),
('description', 'Reference Material - Notes Regarding Data File Content'),
]),
]),
('extras', OrderedDict([
('external_reference', 'BIS-000002'),
('date_released', '2008'),
('date_updated', '2008'),
('temporal_granularity', 'years'),
('temporal_coverage_to', '2008-07-31'),
('temporal_coverage_from', '2007-08-01'),
('geographic_coverage', '111100: United Kingdom (England, Scotland, Wales, Northern Ireland)'),
('geographical_granularity', 'national'),
('agency', u'Higher Education Statistics Agency'),
('precision', 'integer to the nearest 5'),
('taxonomy_url', '-'),
('import_source', 'BIS-%s' % os.path.basename(self._filepath)),
('department', u'Department for Business, Innovation and Skills'),
('update_frequency', 'Never'),
('national_statistic', 'no'),
('categories', '-'),
])
),
])
pkg_dict = self.importer.row_2_package(row_dict)
log = self.importer.get_log()
assert not log, log
PackageDictUtil.check_dict(pkg_dict, expected_pkg_dict)
expected_keys = set([key for key, value in expected_pkg_dict.items()])
keys = set(pkg_dict.keys())
key_difference = expected_keys - keys
assert not key_difference, key_difference
示例5: FieldSet
# 需要导入模块: from sqlalchemy.util import OrderedDict [as 别名]
# 或者: from sqlalchemy.util.OrderedDict import items [as 别名]
#.........这里部分代码省略.........
"""
Like `configure`, but does not undo the effects of a previous call
to `configure` or `reconfigure`.
"""
self.focus = focus
self.readonly = readonly
self.validator = global_validator
self._render_fields = OrderedDict([(field.key, field) for field in self._get_fields(pk, exclude, include, options, use_rendered=True)])
def bind(self, model=None, session=None, data=None, request=None,
with_prefix=True):
"""
Return a copy of this FieldSet or Grid, bound to the given
`model`, `session`, and `data`. The parameters to this method are the
same as in the constructor.
Often you will create and `configure` a FieldSet or Grid at application
startup, then `bind` specific instances to it for actual editing or display.
"""
if not (model is not None or session or data or request):
raise Exception('must specify at least one of {model, session, data, request}')
if not model:
if not self.model:
raise Exception('model must be specified when none is already set')
model = fields._pk(self.model) is None and type(self.model) or self.model
# 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
FieldSet.rebind(mr, model, session, data, request,
with_prefix=with_prefix)
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()]])
mr._request = request
return mr
def rebind(self, model=None, session=None, data=None, request=None,
with_prefix=True):
"""
Like `bind`, but acts on this instance. No return value.
Not all parameters are treated the same; specifically, what happens if they are NOT specified is different:
* if `model` is not specified, the old model is used
* if `session` is not specified, FA tries to re-guess session from the model
* if `data` is not specified, it is rebound to None
* if `request` is specified and not `data` request.POST is used as data.
`request` is also saved to be access by renderers (as
`fs.FIELD.renderer.request`).
* if `with_prefix` is False then a prefix ``{Model}-{pk}`` is added to each data keys
"""
if data is None and request is not None:
if hasattr(request, 'environ') and hasattr(request, 'POST'):
if request.environ.get('REQUEST_METHOD', '').upper() == 'POST':
data = request.POST or None
original_model = model
if model:
if isinstance(model, type):
try:
model = model()
except Exception as e:
示例6: ApplyBatchImpl
# 需要导入模块: from sqlalchemy.util import OrderedDict [as 别名]
# 或者: from sqlalchemy.util.OrderedDict import items [as 别名]
#.........这里部分代码省略.........
if tname != self.temp_table_name:
key = sql_schema._get_table_key(tname, referent_schema)
if key in metadata.tables:
t = metadata.tables[key]
for elem in constraint.elements:
colname = elem._get_colspec().split(".")[-1]
if not t.c.contains_column(colname):
t.append_column(Column(colname, sqltypes.NULLTYPE))
else:
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
else:
op_impl.rename_table(
self.temp_table_name, self.table.name, schema=self.table.schema
)
self.new_table.name = self.table.name
try:
for idx in self._gather_indexes_from_both_tables():
op_impl.create_index(idx)
finally:
self.new_table.name = self.temp_table_name
def alter_column(
self,
table_name,
column_name,
nullable=None,
server_default=False,
示例7: ApplyBatchImpl
# 需要导入模块: from sqlalchemy.util import OrderedDict [as 别名]
# 或者: from sqlalchemy.util.OrderedDict import items [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
#.........这里部分代码省略.........
示例8: ApplyBatchImpl
# 需要导入模块: from sqlalchemy.util import OrderedDict [as 别名]
# 或者: from sqlalchemy.util.OrderedDict import items [as 别名]
#.........这里部分代码省略.........
if len(parts) == 3:
referent_schema = parts[0]
else:
referent_schema = None
if tname != '_alembic_batch_temp':
key = sql_schema._get_table_key(tname, referent_schema)
if key in metadata.tables:
t = metadata.tables[key]
for elem in constraint.elements:
colname = elem._get_colspec().split(".")[-1]
if not t.c.contains_column(colname):
t.append_column(
Column(colname, sqltypes.NULLTYPE)
)
else:
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
else:
op_impl.rename_table(
"_alembic_batch_temp",
self.table.name,
schema=self.table.schema
)
self.new_table.name = self.table.name
try:
for idx in self._gather_indexes_from_both_tables():
op_impl.create_index(idx)
finally:
self.new_table.name = "_alembic_batch_temp"
def alter_column(self, table_name, column_name,
nullable=None,
server_default=False,
name=None,
type_=None,
autoincrement=None,
**kw
):