Here are the examples of the python api sqlalchemy.ext.hybrid.hybrid_property taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
28 Examples
3
Example 1
def _fixture(self, assignable):
Base = declarative_base()
class A(Base):
__tablename__ = 'a'
id = Column(Integer, primary_key=True)
_value = Column("value", String)
@hybrid.hybrid_property
def value(self):
return self._value - 5
if assignable:
@value.setter
def value(self, v):
self._value = v + 5
return A
3
Example 2
def _fixture(self):
Base = declarative_base()
class A(Base):
__tablename__ = 'a'
id = Column(Integer, primary_key=True)
_value = Column("value", String)
@hybrid.hybrid_property
def value(self):
"This is an instance-level docstring"
return self._value
return A
3
Example 3
Project: Flexget Source File: database.py
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
3
Example 4
Project: Flexget Source File: database.py
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)
3
Example 5
Project: Flexget Source File: database.py
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)
3
Example 6
def __call__(self, attr):
return hybrid_property(
fget=self.getter_factory(attr),
fset=self.setter_factory(attr),
expr=self.expr_factory(attr)
)
3
Example 7
Project: sqlalchemy-utils Source File: test_sort_query.py
def test_assigned_hybrid_property(self, session, Article):
def getter(self):
return self.name
Article.some_hybrid = sa.ext.hybrid.hybrid_property(
fget=getter
)
query = session.query(Article)
query = sort_query(query, 'some_hybrid')
assert_contains('ORDER BY article.name ASC', query)
0
Example 8
Project: piecash Source File: sa_extra.py
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,
)
0
Example 9
Project: piecash Source File: sa_extra.py
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,
)
0
Example 10
Project: piecash Source File: _common.py
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)
denom_basis = getattr(self, "{}_basis".format(denom_name), None)
if denom_basis is not None:
denom = denom_basis
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,
)
0
Example 11
def _fixture(self):
Base = declarative_base()
class A(Base):
__tablename__ = 'a'
id = Column(Integer, primary_key=True)
_value = Column("value", String)
@hybrid.hybrid_property
def value(self):
"This is an instance-level docstring"
return int(self._value) - 5
@value.expression
def value(cls):
"This is a class-level docstring"
return func.foo(cls._value) + cls.bar_value
@value.setter
def value(self, v):
self._value = v + 5
@hybrid.hybrid_property
def bar_value(cls):
return func.bar(cls._value)
return A
0
Example 12
Project: sqlalchemy Source File: test_hybrid.py
def _relationship_fixture(self):
Base = declarative_base()
class A(Base):
__tablename__ = 'a'
id = Column(Integer, primary_key=True)
b_id = Column('bid', Integer, ForeignKey('b.id'))
_value = Column("value", String)
@hybrid.hybrid_property
def value(self):
return int(self._value) - 5
@value.expression
def value(cls):
return func.foo(cls._value) + cls.bar_value
@value.setter
def value(self, v):
self._value = v + 5
@hybrid.hybrid_property
def bar_value(cls):
return func.bar(cls._value)
class B(Base):
__tablename__ = 'b'
id = Column(Integer, primary_key=True)
as_ = relationship("A")
return A, B
0
Example 13
Project: sqlalchemy Source File: test_hybrid.py
@classmethod
def setup_class(cls):
from sqlalchemy import literal
symbols = ('usd', 'gbp', 'cad', 'eur', 'aud')
currency_lookup = dict(
((currency_from, currency_to), Decimal(str(rate)))
for currency_to, values in zip(
symbols,
[
(1, 1.59009, 0.988611, 1.37979, 1.02962),
(0.628895, 1, 0.621732, 0.867748, 0.647525),
(1.01152, 1.6084, 1, 1.39569, 1.04148),
(0.724743, 1.1524, 0.716489, 1, 0.746213),
(0.971228, 1.54434, 0.960166, 1.34009, 1),
])
for currency_from, rate in zip(symbols, values)
)
class Amount(object):
def __init__(self, amount, currency):
self.currency = currency
self.amount = amount
def __add__(self, other):
return Amount(
self.amount +
other.as_currency(self.currency).amount,
self.currency
)
def __sub__(self, other):
return Amount(
self.amount -
other.as_currency(self.currency).amount,
self.currency
)
def __lt__(self, other):
return self.amount < other.as_currency(self.currency).amount
def __gt__(self, other):
return self.amount > other.as_currency(self.currency).amount
def __eq__(self, other):
return self.amount == other.as_currency(self.currency).amount
def as_currency(self, other_currency):
return Amount(
currency_lookup[(self.currency, other_currency)] *
self.amount,
other_currency
)
def __clause_element__(self):
# helper method for SQLAlchemy to interpret
# the Amount object as a SQL element
if isinstance(self.amount, (float, int, Decimal)):
return literal(self.amount)
else:
return self.amount
def __str__(self):
return "%2.4f %s" % (self.amount, self.currency)
def __repr__(self):
return "Amount(%r, %r)" % (self.amount, self.currency)
Base = declarative_base()
class BankAccount(Base):
__tablename__ = 'bank_account'
id = Column(Integer, primary_key=True)
_balance = Column('balance', Numeric)
@hybrid.hybrid_property
def balance(self):
"""Return an Amount view of the current balance."""
return Amount(self._balance, "usd")
@balance.setter
def balance(self, value):
self._balance = value.as_currency("usd").amount
cls.Amount = Amount
cls.BankAccount = BankAccount
0
Example 14
Project: Flexget Source File: database.py
def quality_property(text_attr):
def getter(self):
return qualities.Quality(getattr(self, text_attr))
def setter(self, value):
if isinstance(value, str):
setattr(self, text_attr, value)
else:
setattr(self, text_attr, value.name)
class QualComparator(Comparator):
def operate(self, op, other):
if isinstance(other, qualities.Quality):
other = other.name
return op(self.__clause_element__(), other)
def comparator(self):
return QualComparator(getattr(self, text_attr))
prop = hybrid_property(getter, setter)
prop.comparator(comparator)
return prop
0
Example 15
Project: indico Source File: models.py
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)
0
Example 16
@hybrid.hybrid_property
def query( self ):
return Session().query( self.__class__ )
0
Example 17
@hybrid.hybrid_property
def email( self ):
return self._get_contact_mechanism( u'email' )
0
Example 18
@hybrid.hybrid_property
def phone( self ):
return self._get_contact_mechanism( u'phone' )
0
Example 19
Project: Camelot Source File: party.py
@hybrid.hybrid_property
def fax( self ):
return self._get_contact_mechanism( u'fax' )
0
Example 20
Project: Camelot Source File: party.py
@hybrid.hybrid_property
def street1( self ):
return self._get_address_field( u'street1' )
0
Example 21
@hybrid.hybrid_property
def street2( self ):
return self._get_address_field( u'street2' )
0
Example 22
@hybrid.hybrid_property
def city( self ):
return self._get_address_field( u'city' )
0
Example 23
@hybrid.hybrid_property
def street2( self ):
return self._get_address_field( u'street2' )
0
Example 24
Project: Camelot Source File: party.py
@hybrid.hybrid_property
def mechanism( self ):
if self.contact_mechanism != None:
return self.contact_mechanism.mechanism
0
Example 25
Project: Camelot Source File: type_and_status.py
@hybrid.hybrid_property
def current_status( self ):
status_history = self.get_status_history_at()
if status_history != None:
return status_history.classified_by
0
Example 26
Project: sqlalchemy-i18n Source File: builders.py
def generate_hybrid(self, property_name):
"""
Generate a SQLAlchemy hybrid property for given translation model
property.
:param property_name:
Name of the translation model property to generate hybrid property
for.
"""
setattr(
self.model,
property_name,
hybrid_property(
fget=self.getter_factory(property_name),
fset=self.setter_factory(property_name),
expr=lambda cls: getattr(
cls.__translatable__['class'], property_name
)
)
)
0
Example 27
@hybrid.hybrid_property
def data(self):
udata = zlib.decompress(self._data)
return udata
0
Example 28
@hybrid.hybrid_property
def checksum(self):
return self._checksum