In this talk, we'll examine how to use SQLAlchemy ORM and Core in both simple queries and query builder type applications. Next, we'll explore Alembic database migrations and how we can use them to handle database changes.
24. SELECT entries.id AS entries_id,
entries.user_id AS entries_user_id,
entries.phone AS entries_phone,
entries.measurement AS entries_measurement,
entries.insulin AS entries_insulin,
entries.insulin_type AS entries_insulin_type,
entries.carbs AS entries_carbs,
entries.tag AS entries_tag,
entries.three_sixty_id AS entries_three_sixty_id,
entries.entry_time AS entries_entry_time,
entries.created_time AS entries_created_time
FROM entries
WHERE entries.user_id = :user_id_1
AND entries.entry_time > :entry_time_1
ORDER BY ID DESC
25. from sqlalchemy import func
from sqlalchemy.sql import label
results = db.query(
User.group,
label('members', func.count(User.id)),
label(
'total_balance',
func.sum(User.balance)
)
).group_by(User.group).all()
for result in results:
print result.group,
result.members,
result.total_balance
44. unload (
'select * from venue where venueid in (
select venueid from venue order by venueid desc limit 10)'
)
to 's3://mybucket/venue_pipe_'
credentials 'aws_access_key_id=ACCESS_KEY;
aws_secret_access_key=SECRET_KEY';
46. s = select(
[
table.c.discharge_year,
func.count(1).label(
'patient_discharges'),
table.c.zip_code,
], table.c.discharge_year.in_(years)
).group_by(table.c.discharge_year)
s = s.where(table.c.hospital_name == provider)
if 'total_charges' not in unavailable_fields:
s = s.column(
func.sum(table.c.total_charges
).label('patient_charges')
)
s = s.group_by(table.c.zip_code)
s = s.order_by('discharges DESC')
cases = conn.execute(s).fetchall()
52. # A generic, single database configuration.
[alembic]
# path to migration scripts
script_location = alembic
# template used to generate migration files
# file_template = %%(rev)s_%%(slug)s
# set to 'true' to run the environment during
# the 'revision' command, regardless of
autogenerate
# revision_environment = false
sqlalchemy.url = driver://user:pass@localhost/dbname
53. from glu import db
target_metadata = db.metadata
def run_migrations_online():
alembic_config = config.get_section(config.config_ini_section)
from config import SQLALCHEMY_DATABASE_URI
alembic_config['sqlalchemy.url'] = SQLALCHEMY_DATABASE_URI
engine = engine_from_config(
alembic_config,
prefix='sqlalchemy.',
poolclass=pool.NullPool
)