Skip to content

Commit

Permalink
Add files via upload
Browse files Browse the repository at this point in the history
  • Loading branch information
BrendanMartin authored Jan 2, 2019
1 parent bc50479 commit c1f3261
Show file tree
Hide file tree
Showing 10 changed files with 313 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
# 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

# timezone to use when rendering the date
# within the migration file as well as the filename.
# string value is passed to dateutil.tz.gettz()
# leave blank for localtime
# timezone =

# max length of characters to apply to the
# "slug" field
#truncate_slug_length = 40

# set to 'true' to run the environment during
# the 'revision' command, regardless of autogenerate
# revision_environment = false

# set to 'true' to allow .pyc and .pyo files without
# a source .py file to be detected as revisions in the
# versions/ directory
# sourceless = false

# version location specification; this defaults
# to alembic/versions. When using multiple version
# directories, initial revisions must be specified with --version-path
# version_locations = %(here)s/bar %(here)s/bat alembic/versions

# the output encoding used when revision files
# are written from script.py.mako
# output_encoding = utf-8

sqlalchemy.url = driver://user:pass@localhost/dbname


# Logging configuration
[loggers]
keys = root,sqlalchemy,alembic

[handlers]
keys = console

[formatters]
keys = generic

[logger_root]
level = WARN
handlers = console
qualname =

[logger_sqlalchemy]
level = WARN
handlers =
qualname = sqlalchemy.engine

[logger_alembic]
level = INFO
handlers =
qualname = alembic

[handler_console]
class = StreamHandler
args = (sys.stderr,)
level = NOTSET
formatter = generic

[formatter_generic]
format = %(levelname)-5.5s [%(name)s] %(message)s
datefmt = %H:%M:%S
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Generic single-database configuration.
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
from __future__ import with_statement
from alembic import context
from sqlalchemy import engine_from_config, pool
from logging.config import fileConfig

# this is the Alembic Config object, which provides
# access to the values within the .ini file in use.
config = context.config

# Interpret the config file for Python logging.
# This line sets up loggers basically.
fileConfig(config.config_file_name)

import sys, os
sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))

import config as my_config
config.set_main_option('sqlalchemy.url', my_config.DATABASE_URI)

# add your model's MetaData object here
# for 'autogenerate' support
# from myapp import mymodel
# target_metadata = mymodel.Base.metadata
from models import Base
target_metadata = Base.metadata

# other values from the config, defined by the needs of env.py,
# can be acquired:
# my_important_option = config.get_main_option("my_important_option")
# ... etc.


def run_migrations_offline():
"""Run migrations in 'offline' mode.
This configures the context with just a URL
and not an Engine, though an Engine is acceptable
here as well. By skipping the Engine creation
we don't even need a DBAPI to be available.
Calls to context.execute() here emit the given string to the
script output.
"""
url = config.get_main_option("sqlalchemy.url")
context.configure(
url=url, target_metadata=target_metadata, literal_binds=True)

with context.begin_transaction():
context.run_migrations()


def run_migrations_online():
"""Run migrations in 'online' mode.
In this scenario we need to create an Engine
and associate a connection with the context.
"""
connectable = engine_from_config(
config.get_section(config.config_ini_section),
prefix='sqlalchemy.',
poolclass=pool.NullPool)

with connectable.connect() as connection:
context.configure(
connection=connection,
target_metadata=target_metadata
)

with context.begin_transaction():
context.run_migrations()

if context.is_offline_mode():
run_migrations_offline()
else:
run_migrations_online()
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
"""${message}

Revision ID: ${up_revision}
Revises: ${down_revision | comma,n}
Create Date: ${create_date}

"""
from alembic import op
import sqlalchemy as sa
${imports if imports else ""}

# revision identifiers, used by Alembic.
revision = ${repr(up_revision)}
down_revision = ${repr(down_revision)}
branch_labels = ${repr(branch_labels)}
depends_on = ${repr(depends_on)}


def upgrade():
${upgrades if upgrades else "pass"}


def downgrade():
${downgrades if downgrades else "pass"}
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
"""Added price column
Revision ID: c98ef4af563a
Revises:
Create Date: 2018-12-31 13:03:51.242265
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql

# revision identifiers, used by Alembic.
revision = 'c98ef4af563a'
down_revision = None
branch_labels = None
depends_on = None


def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column('books', sa.Column('price', postgresql.MONEY(), nullable=True))
# ### end Alembic commands ###


def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_column('books', 'price')
# ### end Alembic commands ###
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
title: "An Introduction to Statistical Learning: with Applications in R"
author: Gareth James, Daniela Witten, Trevor Hastie, and Robert Tibshirani
pages: 426
published: 01-01-2013
---
title: "The Elements of Statistical Learning: Data Mining, Inference and Prediction"
author: Trevor Hastie, Robert Tibshirani, Jerome Friedman
pages: 745
published: 01-01-2009
---
title: "Pattern Recognition and Machine Learning"
author: Christopher Bishop
pages: 738
published: 04-06-2011
---
title: "Machine Learning: A Probabilistic Perspective"
author: Kevin Murphy
pages: 1104
published: 08-24-2012
---
title: "Deep Learning"
author: Ian Goodfellow, Yoshua Bengio, Aaron Courville, Francis Bach
pages: 775
published: 10-08-2016
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
from crud import Session
from models import Book

s = Session()

books = s.query(Book).all()

for book in books:
price = input(f"Price for '{book.title}': $")
book.price = price
s.add(book)

s.commit()
s.close()
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@

DATABASE_URI = 'postgres+psycopg2://postgres:password@localhost:5432/books'
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
from datetime import datetime

from sqlalchemy import create_engine
from config import DATABASE_URI
from models import Base, Book
from sqlalchemy.orm import sessionmaker
from contextlib import contextmanager
import yaml

engine = create_engine(DATABASE_URI)

Session = sessionmaker(bind=engine)


@contextmanager
def session_scope():
session = Session()
try:
yield session
session.commit()
except Exception:
session.rollback()
raise
finally:
session.close()


def recreate_database():
Base.metadata.drop_all(engine)
Base.metadata.create_all(engine)


def load_yaml():
with session_scope() as s:
for data in yaml.load_all(open('books.yaml')):
book = Book(**data)
s.add(book)


if __name__ == '__main__':
recreate_database()
# add_data()

book = Book(
title='Deep Learning',
author='Ian Goodfellow',
pages=775,
published=datetime(2016, 11, 18)
)
with session_scope() as s:
s.add(book)
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String, Date
from sqlalchemy.dialects.postgresql import MONEY

Base = declarative_base()

class Book(Base):
__tablename__ = 'books'
id = Column(Integer, primary_key=True)
title = Column(String)
author = Column(String)
pages = Column(Integer)
published = Column(Date)
price = Column(MONEY)

def __repr__(self):
return "<Book(title='{}', author='{}', pages={}, published={}, price={})>" \
.format(self.title, self.author, self.pages, self.published, self.price)

0 comments on commit c1f3261

Please sign in to comment.