本文整理汇总了Python中sqlalchemy.sql.and_方法的典型用法代码示例。如果您正苦于以下问题:Python sql.and_方法的具体用法?Python sql.and_怎么用?Python sql.and_使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类sqlalchemy.sql
的用法示例。
在下文中一共展示了sql.and_方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_profit_for_pair
# 需要导入模块: from sqlalchemy import sql [as 别名]
# 或者: from sqlalchemy.sql import and_ [as 别名]
def get_profit_for_pair(exchange, pair):
"""Iterates through all trades for given exchange pair over the course of trading. Starts by subtracting the long positions (the buys) and adding the short positions (the sells) to arrive at the difference (profit"""
"""The buys are always the even rows and the sells are the odd rows (buy always before sell starting from zero)"""
profit = 0
counter = 0
s = select([database.TradingPositions]).where(and_(database.TradingPositions.c.Exchange == exchange, database.TradingPositions.c.Pair == pair))
result = conn.execute(s)
for row in result:
if counter % 2 == 0:
profit = profit - row[5]
counter += 1
else:
profit = profit + row[5]
counter += 1
return profit
示例2: _term_eval
# 需要导入模块: from sqlalchemy import sql [as 别名]
# 或者: from sqlalchemy.sql import and_ [as 别名]
def _term_eval(term, column_variable, column_key):
if term["type"].lower() == "conjunction":
return and_(*((_term_eval(t, column_variable, column_key) for t in term["terms"])))
elif term["type"].lower() == "disjunction":
return or_(*((_term_eval(t, column_variable, column_key) for t in term["terms"])))
elif term["type"].lower() == "literal":
if "key" in term and term["key"]:
key_operator = term.get("key_operator", "IN")
if key_operator is None or key_operator == "IN":
key_condition = column_key.in_(term["key"])
elif key_operator=="ILIKE":
key_condition = or_(*(column_key.ilike(pattern) for pattern in term["key"]))
return and_(column_variable==term["variable"], key_condition)
else:
return column_variable==term["variable"]
示例3: find_all
# 需要导入模块: from sqlalchemy import sql [as 别名]
# 或者: from sqlalchemy.sql import and_ [as 别名]
def find_all(query, model, kwargs):
"""
Returns a query object that ensures that all kwargs
are present.
:param query:
:param model:
:param kwargs:
:return:
"""
conditions = []
kwargs = filter_none(kwargs)
for attr, value in kwargs.items():
if not isinstance(value, list):
value = value.split(",")
conditions.append(get_model_column(model, attr).in_(value))
return query.filter(and_(*conditions))
示例4: validatePCode
# 需要导入模块: from sqlalchemy import sql [as 别名]
# 或者: from sqlalchemy.sql import and_ [as 别名]
def validatePCode(self, sender, event):
productCd = self.proVal.get_text()
productGroup = self.productGroup.get_text()
if self.product_code != productCd:
product = self.session.query(Products).filter(
and_(Products.id == productCd, Products.accGroup == productGroup)).first()
if not product:
self.proVal.modify_base(Gtk.StateType.NORMAL, self.redClr)
msg = _("Product code is invalid")
self.proVal.set_tooltip_text(msg)
self.addStBar.push(1, msg)
self.proNameLbl.set_text("")
self.product = None
else:
self.proVal.modify_base(Gtk.StateType.NORMAL, self.whiteClr)
self.proVal.set_tooltip_text("")
# self.proSelected(code=product.code)
self.proNameLbl.set_text(product.name)
self.productGroup.set_text(product.accGroup)
self.product = product
self.product_code = productCd
示例5: filter_timestamp_column
# 需要导入模块: from sqlalchemy import sql [as 别名]
# 或者: from sqlalchemy.sql import and_ [as 别名]
def filter_timestamp_column(self, ts_col) -> ColumnElement:
"""
Filter timestamp column using this hour interval.
Parameters
----------
ts_col : sqlalchemy column
The timestamp column to filter.
Returns
-------
sqlalchemy.sql.elements.ColumnElement
Sqlalchemy expression representing the filtered timestamp column.
This can be used in WHERE clauses of other sql queries.
"""
return and_(
self.start_hour.filter_timestamp_column(ts_col, cmp_op=greater_or_equal),
self.stop_hour.filter_timestamp_column(ts_col, cmp_op=less_than),
self.period.filter_timestamp_column_by_day_of_week(ts_col),
)
示例6: test_select_whereclause
# 需要导入模块: from sqlalchemy import sql [as 别名]
# 或者: from sqlalchemy.sql import and_ [as 别名]
def test_select_whereclause(self):
t1 = table("t1", column("q"), column("p"))
x = 10
y = 5
def go():
return select([t1]).where(lambda: and_(t1.c.q == x, t1.c.p == y))
self.assert_compile(
go(), "SELECT t1.q, t1.p FROM t1 WHERE t1.q = :x_1 AND t1.p = :y_1"
)
self.assert_compile(
go(), "SELECT t1.q, t1.p FROM t1 WHERE t1.q = :x_1 AND t1.p = :y_1"
)
示例7: _expr
# 需要导入模块: from sqlalchemy import sql [as 别名]
# 或者: from sqlalchemy.sql import and_ [as 别名]
def _expr(self,model,model_param,model_expr):
if not isinstance(model_expr,list):
raise UliwebError("only accept array in @expr, but get '%s'"%(model_expr))
num = len(model_expr)
if (num<2 or num>3):
raise UliwebError("only accept 2 or 3 items in @expr, but get '%s'"%(model_expr))
op = model_expr[-2]
if op=='&':
if num!=3:
raise UliwebError("'&'(and) expression need 3 items, but get '%s'"%(model_expr))
c1 = self._get_filter_condition(model,model_param,model_expr[0],expr=True)
c2 = self._get_filter_condition(model,model_param,model_expr[2],expr=True)
return and_(c1,c2)
elif op=='|':
if num!=3:
raise UliwebError("'|'(or) expression need 3 items, but get '%s'"%(model_expr))
c1 = self._get_filter_condition(model,model_param,model_expr[0],expr=True)
c2 = self._get_filter_condition(model,model_param,model_expr[2],expr=True)
return or_(c1,c2)
elif op=='!':
if num!=2:
raise UliwebError("'!'(not) expression need 2 items, but get '%s'"%(model_expr))
return not_(self._get_filter_condition(model,model_param,model_expr[1],expr=True))
else:
raise UliwebError("unknown operator: '%s'"%(op))
示例8: _create_join_conds
# 需要导入模块: from sqlalchemy import sql [as 别名]
# 或者: from sqlalchemy.sql import and_ [as 别名]
def _create_join_conds(left_sel, right_sel, on):
left_cols = left_sel.columns #lift_inner_cols(left_sel)
right_cols = right_sel.columns #lift_inner_cols(right_sel)
if callable(on):
# callable, like with sql_on arg
conds = [on(left_cols, right_cols)]
else:
# dict-like of form {left: right}
conds = []
for l, r in on.items():
col_expr = left_cols[l] == right_cols[r]
conds.append(col_expr)
return sql.and_(*conds)
# Head ------------------------------------------------------------------------
示例9: get_point_name_by_coor
# 需要导入模块: from sqlalchemy import sql [as 别名]
# 或者: from sqlalchemy.sql import and_ [as 别名]
def get_point_name_by_coor(self,x=None,y=None,z=None):
"""
Get the name of points in the database
params:
name: str
x,y,z: coordinates in current_unit
returns:
point list satisfies the coordiniates if successful or None if failed.
"""
try:
tol=self.session.query(Config).first().tolerance
pts=self.session.query(Point)
scale=self.scale()
if x is not None:
pts=pts.filter(and_((Point.x-x*scale['L'])<tol,(x-Point.x*scale['L'])<tol))
if y is not None:
pts=pts.filter(and_((Point.y-y*scale['L'])<tol,(y-Point.y*scale['L'])<tol))
if z is not None:
pts=pts.filter(and_((Point.z-z*scale['L'])<tol,(z-Point.z*scale['L'])<tol))
names=[pt.name for pt in pts.all()]
return names
except Exception as e:
logger.info(str(e))
self.session.rollback()
return None
示例10: filter_comments_for_view
# 需要导入模块: from sqlalchemy import sql [as 别名]
# 或者: from sqlalchemy.sql import and_ [as 别名]
def filter_comments_for_view(cls, method):
if not current_user or current_user.is_anonymous:
return
return and_(cls.discriminator == COMMENT_ID,
cls.owner_id == current_user.id)
示例11: _get_nonansi_join_whereclause
# 需要导入模块: from sqlalchemy import sql [as 别名]
# 或者: from sqlalchemy.sql import and_ [as 别名]
def _get_nonansi_join_whereclause(self, froms):
clauses = []
def visit_join(join):
if join.isouter:
def visit_binary(binary):
if binary.operator == sql_operators.eq:
if join.right.is_derived_from(binary.left.table):
binary.left = _OuterJoinColumn(binary.left)
elif join.right.is_derived_from(binary.right.table):
binary.right = _OuterJoinColumn(binary.right)
clauses.append(visitors.cloned_traverse(
join.onclause, {}, {'binary': visit_binary}))
else:
clauses.append(join.onclause)
for j in join.left, join.right:
if isinstance(j, expression.Join):
visit_join(j)
elif isinstance(j, expression.FromGrouping):
visit_join(j.element)
for f in froms:
if isinstance(f, expression.Join):
visit_join(f)
if not clauses:
return None
else:
return sql.and_(*clauses)
示例12: from_clause
# 需要导入模块: from sqlalchemy import sql [as 别名]
# 或者: from sqlalchemy.sql import and_ [as 别名]
def from_clause(self):
_from_clause = self._get_table_clause(self.fact_table)
for lookup in self.lookups:
_join_clause_and = []
for (idx, pk) in enumerate(lookup['join']['primary_key']):
fk = lookup['join']['foreign_key'][idx]
fk_table, fk_column = fk.split('.')
pk_table, pk_column = pk.split('.')
fk_table_quoted = sql.quoted_name(fk_table, True)
fk_column_quoted = sql.quoted_name(fk_column, True)
pk_table_quoted = sql.quoted_name(pk_table, True)
pk_column_quoted = sql.quoted_name(pk_column, True)
pk_column = sql.column(fk_column_quoted,
_selectable=sql.table(fk_table_quoted))
fk_column = sql.column(pk_column_quoted,
_selectable=sql.table(pk_table_quoted))
_join_clause_and.append(pk_column == fk_column)
_lookup = _Table(lookup.get('table'), lookup.get('alias'))
_is_left_join = lookup['join']['type'].lower() == 'left'
_from_clause = sql.join(
left=_from_clause,
right=self._get_table_clause(_lookup),
onclause=sql.and_(*_join_clause_and),
isouter=_is_left_join,
)
return _from_clause
示例13: update_fav_sample_field
# 需要导入模块: from sqlalchemy import sql [as 别名]
# 或者: from sqlalchemy.sql import and_ [as 别名]
def update_fav_sample_field(method, user, sample_field_id):
existing_sample_field = (
db.session.query(SampleDataType)
.filter(SampleDataType.sample_data_type_id == sample_field_id)
.first()
)
if not existing_sample_field:
raise Exception("No such sample_field")
if method == "save":
db.session.execute(
user_sampletype_map.insert().values(
user_id=user.user_id,
plot_config_id=existing_sample_field.sample_data_type_id,
)
)
elif method == "delete":
db.session.execute(
user_sampletype_map.delete().where(
and_(
user_sampletype_map.c.user_id == user.user_id,
user_sampletype_map.c.sample_data_type_id
== existing_sample_fielexisting_sample_fieldd.sample_data_type_id,
)
)
)
else:
raise Exception("No such method")
db.session.commit()
示例14: update_fav_report_plot_type
# 需要导入模块: from sqlalchemy import sql [as 别名]
# 或者: from sqlalchemy.sql import and_ [as 别名]
def update_fav_report_plot_type(method, user, plot_info):
existing_plot_config_q = db.session.query(PlotConfig).filter(
PlotConfig.config_name == plot_info[0]
)
if len(plot_info) == 2:
existing_plot_config_q = existing_plot_config_q.filter(
PlotConfig.config_dataset == plot_info[1]
)
existing_plot_config = existing_plot_config_q.first()
if not existing_plot_config:
raise Exception("No such plot")
if method == "save":
db.session.execute(
user_plotconfig_map.insert().values(
user_id=user.user_id, plot_config_id=existing_plot_config.config_id
)
)
elif method == "delete":
db.session.execute(
user_plotconfig_map.delete().where(
and_(
user_plotconfig_map.c.user_id == user.user_id,
user_plotconfig_map.c.plot_config_id
== existing_plot_config.config_id,
)
)
)
else:
raise Exception("No such method")
db.session.commit()
示例15: get_reports_data
# 需要导入模块: from sqlalchemy import sql [as 别名]
# 或者: from sqlalchemy.sql import and_ [as 别名]
def get_reports_data(count=False, user_id=None, filters=None):
if not filters:
filters = []
if count:
report_query = db.session.query(func.count(Report.report_id))
return report_query.one()[0]
else:
reports_query = (
db.session.query(Report, User.username)
.join(User, Report.user_id == User.user_id)
.order_by(Report.report_id)
)
if user_id:
reports_query = reports_query.filter(Report.user_id == user_id)
if filters:
reports_query = reports_query.join(ReportMeta).filter(
and_(
ReportMeta.report_meta_key == filters[0],
ReportMeta.report_meta_value == filters[1],
)
)
reports = reports_query.all()
ret_data = []
for report in reports:
ret = {
"report_id": report[0].report_id,
"report_hash": report[0].report_hash,
"upload_date": report[0].created_at,
"username": report[1],
}
# Get the metadata pairs for this report
report_md_query = db.session.query(ReportMeta).filter(
ReportMeta.report_id == report[0].report_id
)
report_md = report_md_query.all()
for md in report_md:
ret[md.report_meta_key] = md.report_meta_value
ret_data.append(ret)
return ret_data