Хабр Курсы для всех
РЕКЛАМА
Практикум, Хекслет, SkyPro, авторские курсы — собрали всех и попросили скидки. Осталось выбрать!
def get_countries(ids=None, date_from=None, date_to=None):
query = Country.query.order_by(Country.creation_date)
if ids:
query = query.filter(Country.id.in_(ids))
if date_from:
query = query.filter(Country.creation_date >= date_from)
if date_to:
query = query.filter(Country.creation_date <= date_to)
return query.all()
{% sql 'get_countries_by_conds', note='get countries by date conditions or ids' %}
SELECT *
FROM countries
{% if ids %}
WHERE id IN ({{ ids|join(', ') }})
{% endif %}
{% if date_from %}
AND WHERE creation_date >= {{ date_from }}
{% endif %}
{% if date_to %}
AND WHERE creation_date <= {{ date_to }}
{% endif %}
ORDER BY creation_date ASC
{% endsql %}
def get_countries(ids=None, date_from=None, date_to=None):
sql_context = {}
if ids:
sql_context['ids'] = ids
if date_from:
sql_context['date_from'] = date_from # + date format 'YYYY-MM-DD'
if date_to:
sql_context['date_to'] = date_to # + date format 'YYYY-MM-DD'
return country_queries.get_countries_by_conds(**sql_context)
get_countries(date_from='2014-08-11', date_to='2015-01-01')
SELECT *
FROM countries AND WHERE creation_date >= {{ date_from }} AND WHERE creation_date <= {{ date_to }} ORDER BY creation_date ASC
{% sql 'get_countries_by_conds', note='get countries by date conditions or ids' %}
SELECT *
FROM countries
{% if ids %}
WHERE id IN ({{ ids|join(', ') }})
{% endif %}
{% if date_from %}
{% if ids %} AND {% endif %} WHERE creation_date >= {{ date_from }}
{% endif %}
{% if date_to %}
{% if ids or date_from %} AND {% endif %} WHERE creation_date <= {{ date_to }}
{% endif %}
ORDER BY creation_date ASC
{% endsql %}
{% sql 'get_countries', note='get countries' %}
SELECT *
FROM countries
{% if conditions %}
{{ conditions|join(' AND ') }}
{% endif %}
ORDER BY creation_date ASC
{% endsql %}
{% sql 'cond_ids_in_countries' %}
WHERE id IN ({{ ids|join(', ') }})
{% endsql %}
{% sql 'cond_date_from_countries' %}
WHERE creation_date >= {{ date_from }}
{% endsql %}
{% sql 'cond_date_to_countries' %}
WHERE creation_date <= {{ date_to }}
{% endsql %}
def get_countries(ids=None, date_from=None, date_to=None):
sql_conditions = []
if ids:
cond = country_queries.cond_ids_in_countries(ids=ids)
sql_conditions.append(cond)
if date_from:
cond = country_queries.cond_date_from_countries(date_from=date_from)
sql_conditions.append(cond)
if date_to:
cond = country_queries.cond_date_to_countries(date_to=date_to)
sql_conditions.append(cond)
return country_queries.get_countries(conditions=sql_conditions)
# --- sqlutils.py -------------------------------
def wrap_int(num):
assert isinstance(num, int)
return str(int(num))
def wrap_dt(dt):
assert isinstance(dt, datetime.datetime)
return "'{}'".format(dt.isoformat())
def in_list(lst, wrap=wrap_int):
return "IN ({})".format(", ".join(wrap(x) for x in lst))
def select(*args):
if args:
return "SELECT {}".format(", ".join(args))
else:
return "SELECT *"
def where(*args, glue="AND"):
args = [x for x in args if x]
if args:
return "WHERE {}".format(" {} ".format(glue).join(args))
else:
return ""
def order_by(column, asc=True):
return "ORDER BY {} {}".format(column, asc and "ASC" or "DESC")
# --- model.py ----------------------------------
def sql_countries_by_conds(ids=None, date_from=None, date_to=None, asc=True):
""" get countries by date conditions or ids """
return """
SELECT *
FROM "countries"
{where}
ORDER BY "creation_date" {asc}
""".format(
where=where(
ids is not None and "id {}".format(in_list(ids)),
date_from and "creation_date >= {}".format(wrap_dt(date_from)),
date_to and "creation_date <= {}".format(wrap_dt(date_to))
),
asc=asc and "ASC" or "DESC"
)
{% sql 'get_countries_by_conds', note='get countries by date conditions or ids' %}
SELECT *
FROM "countries"
{{ where(
ids != None and "id {}".format(in_list(ids)),
date_from and "creation_date >= {}".format(wrap_dt(date_from)),
date_to and "creation_date <= {}".format(wrap_dt(date_to))
) }}
ORDER BY "creation_date" ASC
{% endsql %}
{% macro hello_world(a, b, c=None, d='test') %}
Hello World {{ a }} {{ b }} {{ c }} {{ d }}
{% endmacro %}
{{ hello_world(1, 2, 3, d='Hi')
Алхимия чудесным алхимическим образом убивает всю асинхронность выполнения обработчика блокирующими вызовами в базу
Session(), которую нельзя забывать возвращать в Pool используя Session.remove():As discussed in the section When do I construct a Session, when do I commit it, and when do I close it?, a web application is architected around the concept of a web request, and integrating such an application with the Session usually implies that the Session will be associated with that request. As it turns out, most Python web frameworks, with notable exceptions such as the asynchronous frameworks Twisted and Tornado, use threads in a simple way, such that a particular web request is received, processed, and completed within the scope of a single worker thread. When the request ends, the worker thread is released to a pool of workers where it is available to handle another request.
def _sql(fn):
def wrapped(*args):
return db.session.execute( fn(*args) )
return wrapped
@_sql
def page_count(self):
return "select count(*) from pages"
{{ page.page_count() }}
Snaql. Raw SQL в Python-проектах