本文整理汇总了Python中sqlalchemy.ext.hybrid.hybrid_property函数的典型用法代码示例。如果您正苦于以下问题:Python hybrid_property函数的具体用法?Python hybrid_property怎么用?Python hybrid_property使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了hybrid_property函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: url_id
def url_id(cls):
"""The URL id"""
if cls.__uuid_primary_key__:
def url_id_func(self):
"""The URL id, UUID primary key rendered as a hex string"""
return self.id.hex
def url_id_is(cls):
return SqlHexUuidComparator(cls.id)
url_id_func.__name__ = 'url_id'
url_id_property = hybrid_property(url_id_func)
url_id_property = url_id_property.comparator(url_id_is)
return url_id_property
else:
def url_id_func(self):
"""The URL id, integer primary key rendered as a string"""
return six.text_type(self.id)
def url_id_expression(cls):
"""The URL id, integer primary key"""
return cls.id
url_id_func.__name__ = 'url_id'
url_id_property = hybrid_property(url_id_func)
url_id_property = url_id_property.expression(url_id_expression)
return url_id_property
开发者ID:hasgeek,项目名称:coaster,代码行数:27,代码来源:mixins.py
示例2: decorator
def decorator(func):
if not info.get('filterable', True):
ret = property(func)
else:
ret = hybrid_property(func)
ret.fget.info = info
return ret
开发者ID:MoebiusSolutions,项目名称:sqlstrainer,代码行数:7,代码来源:strainer.py
示例3: createSignature
def createSignature(cls):
'''
Create the signature name link, only one can be created.
'''
def fget(self):
if self.signature: return self.signature.name
def fset(self, name):
assert isinstance(name, str), 'Invalid signature name %s' % name
name = name.strip()
assert name, 'Empty string is not a valid signature name'
session = openSession()
try: signatureId, = session.query(Signature.id).filter(Signature.name == name).one()
except NoResultFound:
signature = Signature()
signature.name = name
session.add(signature)
session.flush((signature,))
signatureId = signature.id
self.signatureId = signatureId
validation = validate(Mandatory, lambda prop: MaxLen(prop, columnFor(Signature.name).type.length))
return validation(hybrid_property(fget, fset, expr=joinedExpr(Signature, 'name')))
开发者ID:cristidomsa,项目名称:Ally-Py,代码行数:25,代码来源:acl_intern.py
示例4: get_sqlalchemy_mapping
def get_sqlalchemy_mapping(self, registry, namespace, fieldname,
properties):
"""Return the property of the field
:param registry: current registry
:param namespace: name of the model
:param fieldname: name of the field
:param properties: properties known to the model
"""
def wrap(method):
m = self.kwargs.get(method)
if m is None:
return None
def function_method(model_self, *args, **kwargs):
if method == 'fget':
cls = registry.get(model_self.__registry_name__)
if model_self is cls:
return hasattr(model_self, m)
return getattr(model_self, m)(*args, **kwargs)
return function_method
fget = wrap('fget')
fset = wrap('fset')
fdel = wrap('fdel')
fexpr = wrap('fexpr')
self.format_label(fieldname)
properties['loaded_fields'][fieldname] = self.label
return hybrid_property(fget, fset, fdel=fdel, expr=fexpr)
开发者ID:AnyBlok,项目名称:AnyBlok,代码行数:33,代码来源:field.py
示例5: override_attr
def override_attr(attr_name, parent_name, fget=None):
"""Create property that overrides an attribute coming from parent.
In order to ensure setter functionality at creation time, ``parent`` must be
initialized before the overriden attribute.
:param attr_name: The name of the attribute to be overriden.
:param parent_name: The name of the attribute from which to override the attribute.
:param fget: Getter for own property
"""
own_attr_name = '_' + attr_name
def _get(self):
parent = getattr(self, parent_name)
attr = getattr(self, own_attr_name)
fget_ = (lambda self, __: attr) if fget is None else fget
return fget_(self, own_attr_name) if attr is not None or not parent else getattr(parent, attr_name)
def _set(self, value):
parent = getattr(self, parent_name)
own_value = getattr(self, own_attr_name)
if not parent or own_value is not None or value != getattr(parent, attr_name):
setattr(self, own_attr_name, value)
def _expr(cls):
return getattr(cls, own_attr_name)
return hybrid_property(_get, _set, expr=_expr)
开发者ID:ThiefMaster,项目名称:indico,代码行数:29,代码来源:models.py
示例6: decorate
def decorate(func):
name = func.__name__
@wraps(func)
def fget(self):
obj = getattr(self, relation)
if not obj:
return default
else:
return getattr(obj.name)
hybrid = hybrid_property(fget)
if class_:
def fset(self, value):
obj = getattr(self, relation)
if not obj:
obj = class_(**class_kwargs)
setattr(self, relation, obj)
setattr(obj, name, value)
hybrid.setter(fset)
if expression:
def expr(cls):
return expression
hybrid.expression(expr)
return hybrid
开发者ID:yimiqisan,项目名称:qstudio,代码行数:29,代码来源:hybrid.py
示例7: test_attrs_props_prop_added_after_configure
def test_attrs_props_prop_added_after_configure(self):
class AnonClass(object):
pass
from sqlalchemy.orm import mapper, column_property
from sqlalchemy.ext.hybrid import hybrid_property
m = mapper(AnonClass, self.tables.users)
eq_(
set(inspect(AnonClass).attrs.keys()),
set(['id', 'name']))
eq_(
set(inspect(AnonClass).all_orm_descriptors.keys()),
set(['id', 'name']))
m.add_property('q', column_property(self.tables.users.c.name))
def desc(self):
return self.name
AnonClass.foob = hybrid_property(desc)
eq_(
set(inspect(AnonClass).attrs.keys()),
set(['id', 'name', 'q']))
eq_(
set(inspect(AnonClass).all_orm_descriptors.keys()),
set(['id', 'name', 'q', 'foob']))
开发者ID:m32,项目名称:sqlalchemy,代码行数:27,代码来源:test_inspect.py
示例8: iri_class_decorator
def iri_class_decorator(klass):
iri_hpropname = '_'+iri_propname
setattr(klass, iri_hpropname,
column_property(id_to_iri(getattr(klass, iri_id_colname))))
def iri_accessor(self):
return getattr(self, iri_hpropname)
def iri_expression(klass):
return id_to_iri(getattr(klass, iri_id_colname))
def iri_setter(self, val):
setattr(self, iri_hpropname, val)
setattr(self, iri_id_colname, iri_to_id(val))
def iri_deleter(self):
setattr(self, iri_id_colname, None)
col = getattr(klass, iri_id_colname)
if not col.property.columns[0].nullable:
iri_deleter = None
prop = hybrid_property(
iri_accessor, iri_setter, iri_deleter, iri_expression)
setattr(klass, iri_propname, prop)
return klass
开发者ID:philippeluickx,项目名称:virtuoso-python,代码行数:25,代码来源:alchemy.py
示例9: pure_slot_property
def pure_slot_property(slot_name, slot_transform=lambda x: x):
"""
Create a property (class must have slots) that maps to a slot
:param slot_name: name of the slot
:param slot_transform: transformation to operate before assigning value
:return:
"""
def fget(self):
# return None if the slot does not exist. alternative could be to raise an exception
try:
return self[slot_name].value
except KeyError:
return None
def fset(self, value):
v = slot_transform(value)
if v is None:
if slot_name in self:
del self[slot_name]
else:
self[slot_name] = v
return hybrid_property(
fget=fget,
fset=fset,
)
开发者ID:chrisberkhout,项目名称:piecash,代码行数:27,代码来源:sa_extra.py
示例10: mapped_to_slot_property
def mapped_to_slot_property(col, slot_name, slot_transform=lambda x: x):
"""Assume the attribute in the class as the same name as the table column with "_" prepended"""
col_name = "_{}".format(col.name)
def fget(self):
return getattr(self, col_name)
def fset(self, value):
v = slot_transform(value)
if v is None:
if slot_name in self:
del self[slot_name]
else:
self[slot_name] = v
setattr(self, col_name, value)
def expr(cls):
return col
return hybrid_property(
fget=fget,
fset=fset,
expr=expr,
)
开发者ID:chrisberkhout,项目名称:piecash,代码行数:25,代码来源:sa_extra.py
示例11: summarized_property
def summarized_property(name):
""" Adds an attribute as hybrid_property which returns the sum of the
underlying results if called.
Requires the class to define two aggregation functions.
Usage::
class Model():
votes = summarized_property('votes')
results = relationship('Result', ...)
def aggregate_results(self, attribute):
return sum(getattr(res, attribute) for res in self.results)
@staticmethod
def aggregate_results_expression(cls, attribute):
expr = select([func.sum(getattr(Result, attribute))])
expr = expr.where(Result.xxx_id == cls.id)
expr = expr.label(attribute)
return expr
"""
def getter(self):
return self.aggregate_results(name)
def expression(cls):
return cls.aggregate_results_expression(cls, name)
return hybrid_property(getter, expr=expression)
开发者ID:OneGov,项目名称:onegov.ballot,代码行数:32,代码来源:mixins.py
示例12: closure
def closure(cls):
class_name = cls.__name__ + 'Localized'
tablename = plural_name(underscorize(class_name))
if db.metadata.tables.get(tablename) is not None:
return
# TODO: pass language from the babel detection
lang = u'en'
cls_columns = cls.__table__.get_children()
columns = dict([(c.name, c.copy()) for c in cls_columns if isinstance(c.type, (db.Unicode, db.UnicodeText))])
localized_names = columns.keys()
columns.update({
'parent_id': db.Column(db.Integer, db.ForeignKey(cls.__tablename__ + '.id'), nullable=False),
'parent': db.relationship(cls, backref='localized_ref'),
'locale': db.Column(db.Unicode(255), default=lang, index=True)
})
cls_localized = type(class_name, (db.Model, CRUDMixin), columns)
for field in localized_names:
def getter(self):
localized = cls_localized.query.filter_by(parent_id=self.id, locale=lang).first()
return getattr(localized, field) or None
def setter(self, value):
localized = cls_localized.query.filter_by(parent_id=self.id, locale=lang).first() or cls_localized(parent=self, locale=lang)
setattr(localized, field, value)
localized.save()
def expression(self):
return db.Query(columns[field]).filter(cls_localized.parent_id == self.id, cls_localized.locale == lang).as_scalar()
setattr(cls, field, hybrid_property(getter, setter, expr=expression))
closure(cls)
开发者ID:oksana-slu,项目名称:sqlfla,代码行数:35,代码来源:decorators.py
示例13: ignore_case_property
def ignore_case_property(text_attr):
def getter(self):
return CaseInsensitiveWord(getattr(self, text_attr))
def setter(self, value):
setattr(self, text_attr, value)
return hybrid_property(getter, setter)
开发者ID:JorisDeRieck,项目名称:Flexget,代码行数:8,代码来源:database.py
示例14: hybrid_property_gncnumeric
def hybrid_property_gncnumeric(num_col, denom_col):
"""Return an hybrid_property handling a Decimal represented by a numerator and a
denominator column.
It assumes the python field related to the sqlcolumn is named as _sqlcolumn.
:type num_col: sqlalchemy.sql.schema.Column
:type denom_col: sqlalchemy.sql.schema.Column
:return: sqlalchemy.ext.hybrid.hybrid_property
"""
num_name, denom_name = "_{}".format(num_col.name), "_{}".format(denom_col.name)
name = num_col.name.split("_")[0]
def fset(self, d):
if d is None:
num, denom = None, None
else:
if isinstance(d, tuple):
d = Decimal(d[0]) / d[1]
elif isinstance(d, (int, int, str)):
d = Decimal(d)
elif isinstance(d, float):
raise TypeError(("Received a floating-point number {} where a decimal is expected. " +
"Use a Decimal, str, or int instead").format(d))
elif not isinstance(d, Decimal):
raise TypeError(("Received an unknown type {} where a decimal is expected. " +
"Use a Decimal, str, or int instead").format(type(d).__name__))
sign, digits, exp = d.as_tuple()
denom = 10 ** max(-exp, 0)
denom_basis = getattr(self, "{}_basis".format(denom_name), None)
if denom_basis is not None:
denom = denom_basis
num = int(d * denom)
if not ((-MAX_NUMBER < num < MAX_NUMBER) and (-MAX_NUMBER < denom < MAX_NUMBER)):
raise ValueError(("The amount '{}' cannot be represented in GnuCash. " +
"Either it is too large or it has too many decimals").format(d))
setattr(self, num_name, num)
setattr(self, denom_name, denom)
def fget(self):
num, denom = getattr(self, num_name), getattr(self, denom_name)
if num is None:
return
else:
return Decimal(num) / denom
def expr(cls):
# todo: cast into Decimal for postgres and for sqlite (for the latter, use sqlite3.register_converter ?)
return (cast(num_col, Float) / denom_col).label(name)
return hybrid_property(
fget=fget,
fset=fset,
expr=expr,
)
开发者ID:sdementen,项目名称:piecash,代码行数:58,代码来源:_common.py
示例15: year_property
def year_property(date_attr):
def getter(self):
date = getattr(self, date_attr)
return date and date.year
def expr(cls):
return extract('year', getattr(cls, date_attr))
return hybrid_property(getter, expr=expr)
开发者ID:JorisDeRieck,项目名称:Flexget,代码行数:9,代码来源:database.py
示例16: assign_attr_getter_setters
def assign_attr_getter_setters(self, attr):
setattr(
self.model,
attr,
hybrid_property(
fget=translation_getter_factory(attr),
fset=translation_setter_factory(attr),
expr=lambda cls: getattr(cls.__translatable__['class'], attr)
)
)
开发者ID:jaredye,项目名称:sqlalchemy-i18n,代码行数:10,代码来源:builders.py
示例17: synonym
def synonym(name):
"""
Utility function mimicking the behavior of the old SA synonym function
with the new hybrid property semantics.
"""
return hybrid_property(
lambda inst: getattr(inst, name),
lambda inst, value: setattr(inst, name, value),
expr=lambda cls: getattr(cls, name),
)
开发者ID:helixyte,项目名称:everest,代码行数:10,代码来源:utils.py
示例18: quality_requirement_property
def quality_requirement_property(text_attr):
def getter(self):
return qualities.Requirements(getattr(self, text_attr))
def setter(self, value):
if isinstance(value, str):
setattr(self, text_attr, value)
else:
setattr(self, text_attr, value.text)
prop = hybrid_property(getter, setter)
return prop
开发者ID:JorisDeRieck,项目名称:Flexget,代码行数:12,代码来源:database.py
示例19: get_property
def get_property(self, registry, namespace, fieldname, properties):
"""Return the property of the field
:param registry: current registry
:param namespace: name of the model
:param fieldname: name of the field
:param properties: properties known to the model
"""
return hybrid_property(
self.wrap_getter_column(fieldname),
self.wrap_setter_column(fieldname),
expr=self.wrap_expr_column(fieldname))
开发者ID:petrus-v,项目名称:AnyBlok,代码行数:12,代码来源:field.py
示例20: hybrid_property_gncnumeric
def hybrid_property_gncnumeric(num_col, denom_col):
"""Return an hybrid_property handling a Decimal represented by a numerator and a denominator column.
It assumes the python field related to the sqlcolumn is named as _sqlcolumn.
:type num_col: sqlalchemy.sql.schema.Column
:type denom_col: sqlalchemy.sql.schema.Column
:return: sqlalchemy.ext.hybrid.hybrid_property
"""
num_name, denom_name = "_{}".format(num_col.name), "_{}".format(denom_col.name)
name = num_col.name.split("_")[0]
def fset(self, d):
if d is None:
num, denom = None, None
else:
if isinstance(d, tuple):
d = Decimal(d[0]) / d[1]
elif isinstance(d, (float, int, long, str)):
d = Decimal(d)
assert isinstance(d, Decimal)
sign, digits, exp = d.as_tuple()
denom = 10 ** max(-exp, 0)
# print num_name, denom,
denom_basis = getattr(self, "{}_basis".format(denom_name), None)
if denom_basis is not None:
# print "got a basis for ", self, denom_basis
denom = denom_basis
# print denom
num = int(d * denom)
setattr(self, num_name, num)
setattr(self, denom_name, denom)
def fget(self):
num, denom = getattr(self, num_name), getattr(self, denom_name)
if num is None:
return
else:
return Decimal(num) / denom
def expr(cls):
# todo: cast into Decimal for postgres and for sqlite (for the latter, use sqlite3.register_converter ?)
return (cast(num_col, Float) / denom_col).label(name)
return hybrid_property(
fget=fget,
fset=fset,
expr=expr,
)
开发者ID:chrisberkhout,项目名称:piecash,代码行数:52,代码来源:_common.py
注:本文中的sqlalchemy.ext.hybrid.hybrid_property函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论