Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

DS12 Unit 3 Sprint 3 - Lawrence Kimsey #167

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -102,3 +102,10 @@ venv.bak/

# mypy
.mypy_cache/

# PyCharm project files
.idea

# Development database:
*.db
*.sqlite3
19 changes: 19 additions & 0 deletions Pipfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
[[source]]
name = "pypi"
url = "https://pypi.org/simple"
verify_ssl = true

[dev-packages]

[packages]
flask = "*"
flask-sqlalchemy = "*"
flask-migrate = "*"
basilica = "*"
python-dotenv = "*"
requests = "*"
tweepy = "*"
scikit-learn = "*"

[requires]
python_version = "3.7"
346 changes: 346 additions & 0 deletions Pipfile.lock

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions migrations/README
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Generic single-database configuration.
45 changes: 45 additions & 0 deletions migrations/alembic.ini
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
# A generic, single database configuration.

[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


# 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
96 changes: 96 additions & 0 deletions migrations/env.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
from __future__ import with_statement

import logging
from logging.config import fileConfig

from sqlalchemy import engine_from_config
from sqlalchemy import pool

from alembic import context

# 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)
logger = logging.getLogger('alembic.env')

# add your model's MetaData object here
# for 'autogenerate' support
# from myapp import mymodel
# target_metadata = mymodel.Base.metadata
from flask import current_app
config.set_main_option(
'sqlalchemy.url',
str(current_app.extensions['migrate'].db.engine.url).replace('%', '%%'))
target_metadata = current_app.extensions['migrate'].db.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.

"""

# this callback is used to prevent an auto-migration from being generated
# when there are no changes to the schema
# reference: http://alembic.zzzcomputing.com/en/latest/cookbook.html
def process_revision_directives(context, revision, directives):
if getattr(config.cmd_opts, 'autogenerate', False):
script = directives[0]
if script.upgrade_ops.is_empty():
directives[:] = []
logger.info('No changes in schema detected.')

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,
process_revision_directives=process_revision_directives,
**current_app.extensions['migrate'].configure_args
)

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


if context.is_offline_mode():
run_migrations_offline()
else:
run_migrations_online()
24 changes: 24 additions & 0 deletions migrations/script.py.mako
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"}
45 changes: 45 additions & 0 deletions migrations/versions/505cb269b18c_.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
"""empty message

Revision ID: 505cb269b18c
Revises:
Create Date: 2020-03-26 16:16:14.208086

"""
from alembic import op
import sqlalchemy as sa


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


def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('user',
sa.Column('id', sa.BigInteger(), nullable=False),
sa.Column('screen_name', sa.String(length=128), nullable=False),
sa.Column('name', sa.String(), nullable=True),
sa.Column('location', sa.String(), nullable=True),
sa.Column('followers_count', sa.Integer(), nullable=True),
sa.Column('latest_tweet_id', sa.BigInteger(), nullable=True),
sa.PrimaryKeyConstraint('id')
)
op.create_table('tweet',
sa.Column('id', sa.BigInteger(), nullable=False),
sa.Column('user_id', sa.BigInteger(), nullable=True),
sa.Column('full_text', sa.String(length=500), nullable=True),
sa.Column('embedding', sa.PickleType(), nullable=True),
sa.ForeignKeyConstraint(['user_id'], ['user.id'], ),
sa.PrimaryKeyConstraint('id')
)
# ### end Alembic commands ###


def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_table('tweet')
op.drop_table('user')
# ### end Alembic commands ###
7 changes: 7 additions & 0 deletions notes.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
Flask commands:

set FLASK_APP=web_app
flask db init
flask db migrate
flask db upgrade
flask run
Binary file added statmodels/latest_model.pkl
Binary file not shown.
32 changes: 32 additions & 0 deletions web_app/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
# web_app/__init__.py

from flask import Flask

from web_app.models import db, migrate
from web_app.routes.home_routes import home_routes
from web_app.routes.book_routes import book_routes
from web_app.routes.twitter_routes import twitter_routes
from web_app.routes.admin_routes import admin_routes
from web_app.routes.stats_routes import stats_routes


def create_app():
app = Flask(__name__)

app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///web_app_12.db"

db.init_app(app)
migrate.init_app(app, db)

app.register_blueprint(home_routes)
app.register_blueprint(book_routes)
app.register_blueprint(twitter_routes)
app.register_blueprint(admin_routes)
app.register_blueprint(stats_routes)

return app


if __name__ == "__main__":
my_app = create_app()
my_app.run(debug=True)
43 changes: 43 additions & 0 deletions web_app/iris_classifier.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
# web_app/iris_classifier.py

import os
import pickle

from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression

MODEL_FILEPATH = os.path.join(os.path.dirname(__file__), "..", "statmodels", "latest_model.pkl")


def train_and_save_model():
print("TRAINING THE MODEL...")
X, y = load_iris(return_X_y=True)
classifier = LogisticRegression() # for example
classifier.fit(X, y)

print("SAVING THE MODEL...")
with open(MODEL_FILEPATH, "wb") as model_file:
pickle.dump(classifier, model_file)

return classifier


def load_model():
print("LOADING THE MODEL...")
with open(MODEL_FILEPATH, "rb") as model_file:
saved_model = pickle.load(model_file)
return saved_model


if __name__ == "__main__":
train_and_save_model()

clf = load_model()
print("CLASSIFIER:", clf)

X, y = load_iris(return_X_y=True) # just to have some data to use when predicting
inputs = X[:2, :]
print(type(inputs), inputs)

result = clf.predict(inputs)
print("RESULT:", result)
56 changes: 56 additions & 0 deletions web_app/models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
# web_app/models.py

from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate

db = SQLAlchemy()

migrate = Migrate()


class Book(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(128))
author_id = db.Column(db.String(128))


class User(db.Model):
id = db.Column(db.BigInteger, primary_key=True)
screen_name = db.Column(db.String(128), nullable=False)
name = db.Column(db.String)
location = db.Column(db.String)
followers_count = db.Column(db.Integer)
latest_tweet_id = db.Column(db.BigInteger)


class Tweet(db.Model):
id = db.Column(db.BigInteger, primary_key=True)
user_id = db.Column(db.BigInteger, db.ForeignKey("user.id"))
full_text = db.Column(db.String(500))
embedding = db.Column(db.PickleType)

user = db.relationship("User", backref=db.backref("tweets", lazy=True))


def parse_records(database_records):
"""
A helper method for converting a list of database record objects into a list of dictionaries, so they can be returned as JSON

Param: database_records (a list of db.Model instances)

Example: parse_records(User.query.all())

Returns: a list of dictionaries, each corresponding to a record, like...
[
{"id": 1, "title": "Book 1"},
{"id": 2, "title": "Book 2"},
{"id": 3, "title": "Book 3"},
]
"""
parsed_records = []
for record in database_records:
print(record)
parsed_record = record.__dict__
del parsed_record["_sa_instance_state"]
parsed_records.append(parsed_record)
return parsed_records
Loading