Skip to content
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
Binary file added .DS_Store
Binary file not shown.
1 change: 1 addition & 0 deletions Procfile
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
web: gunicorn manager:app --log-file=-
84 changes: 84 additions & 0 deletions manage.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
#!/usr/bin/env python
import csv
import os
import random
from datetime import datetime

from flask.ext.script import Manager, Server
from flask.ext.migrate import MigrateCommand
from flask.ext.script.commands import ShowUrls, Clean

from stat_tracker import create_app, db, models


HERE = os.path.abspath(os.path.dirname(__file__))
TEST_PATH = os.path.join(HERE, 'tests')

app = create_app()
manager = Manager(app)
manager.add_command('server', Server())
manager.add_command('db', MigrateCommand)
manager.add_command('show-urls', ShowUrls())
manager.add_command('clean', Clean())


@manager.shell
def make_shell_context():
""" Creates a python REPL with several default imports
in the context of the app
"""

return dict(app=app, db=db, Book=models.Book, User=models.User)


@manager.command
def test():
"""Run the tests."""
import pytest

exit_code = pytest.main([TEST_PATH, '--verbose'])
return exit_code


# @manager.command
# def seed_books():
# """Seed the books with all books in seed_books.csv."""
# books_added = 0
# books_updated = 0
# with open('seed_books.csv') as csvfile:
# reader = csv.DictReader(csvfile)
# for row in reader:
# book = models.Book.query.filter_by(url=row['url']).first()
# if book is None:
# book = models.Book()
# books_added += 1
# else:
# books_updated += 1
# for key, value in row.items():
# setattr(book, key, value)
# db.session.add(book)
# db.session.commit()
# print("{} books added, {} books updated.".format(books_added, books_updated))
#
#
# @manager.command
# def seed_clicks():
# """Add a bunch of click data."""
# max_time = int(datetime.now().timestamp())
# min_time = max_time - (30 * 24 * 60 * 60)
# center = min_time + (max_time - min_time) / 2
# stdev = 5 * 24 * 60 * 60
#
# books = models.Book.query.all()
# for book in books:
# median_date = random.gauss(center, stdev)
# for _ in range(random.randint(100, 500)):
# click = models.Click(
# book=book,
# clicked_at=datetime.fromtimestamp(random.gauss(median_date, stdev)))
# db.session.add(click)
# db.session.commit()


if __name__ == '__main__':
manager.run()
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.
Binary file added migrations/__pycache__/env.cpython-34.pyc
Binary file not shown.
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
73 changes: 73 additions & 0 deletions migrations/env.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
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)

# 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', current_app.config.get('SQLALCHEMY_DATABASE_URI'))
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)

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.

"""
engine = engine_from_config(
config.get_section(config.config_ini_section),
prefix='sqlalchemy.',
poolclass=pool.NullPool)

connection = engine.connect()
context.configure(
connection=connection,
target_metadata=target_metadata
)

try:
with context.begin_transaction():
context.run_migrations()
finally:
connection.close()

if context.is_offline_mode():
run_migrations_offline()
else:
run_migrations_online()

22 changes: 22 additions & 0 deletions migrations/script.py.mako
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
"""${message}

Revision ID: ${up_revision}
Revises: ${down_revision}
Create Date: ${create_date}

"""

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

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

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


def downgrade():
${downgrades if downgrades else "pass"}
53 changes: 53 additions & 0 deletions migrations/versions/4f8a762829b_.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
"""empty message

Revision ID: 4f8a762829b
Revises: None
Create Date: 2015-03-01 13:51:59.075898

"""

# revision identifiers, used by Alembic.
revision = '4f8a762829b'
down_revision = None

from alembic import op
import sqlalchemy as sa


def upgrade():
### commands auto generated by Alembic - please adjust! ###
op.create_table('user',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.String(length=255), nullable=False),
sa.Column('email', sa.String(length=255), nullable=False),
sa.Column('encrypted_password', sa.String(length=60), nullable=True),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('email')
)
op.create_table('activity',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('activity_name', sa.String(length=255), nullable=False),
sa.Column('measurement', sa.String(length=255), nullable=False),
sa.Column('user_id', sa.Integer(), nullable=True),
sa.ForeignKeyConstraint(['user_id'], ['user.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_table('stat',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('value', sa.Integer(), nullable=True),
sa.Column('recorded_at', sa.DateTime(), nullable=True),
sa.Column('user_id', sa.Integer(), nullable=True),
sa.Column('activity_id', sa.Integer(), nullable=True),
sa.ForeignKeyConstraint(['activity_id'], ['activity.id'], ),
sa.ForeignKeyConstraint(['user_id'], ['user.id'], ),
sa.PrimaryKeyConstraint('id')
)
### end Alembic commands ###


def downgrade():
### commands auto generated by Alembic - please adjust! ###
op.drop_table('stat')
op.drop_table('activity')
op.drop_table('user')
### end Alembic commands ###
Binary file not shown.
43 changes: 43 additions & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
# Everything needed in production

## Flask
Flask==0.10.1
MarkupSafe==0.23
Werkzeug==0.10.1
Jinja2==2.7.3
itsdangerous==0.24

## Database
Flask-SQLAlchemy==2.0
SQLAlchemy==0.9.8

## Migrations
Flask-Migrate==1.3.0

## Forms
Flask-WTF==0.11
WTForms==2.0.2

## Login and users
Flask-Login==0.2.11
Flask-Bcrypt==0.6.2

## Management script
Flask-Script==2.0.5

## Config
flask-appconfig==0.9.1

## Heroku
gunicorn==19.2.1
psycopg2==2.6

# Everything the developer needs in addition to the production requirements

Flask-DebugToolbar==0.9.1

matplotlib

## Testing
pytest>=2.6.4
webtest
1 change: 1 addition & 0 deletions runtime.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
python-3.4.2
Binary file added stat_tracker/.DS_Store
Binary file not shown.
42 changes: 42 additions & 0 deletions stat_tracker/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
from flask import Flask
from flask.ext.wtf import CsrfProtect

from .extensions import (
db,
migrate,
#debug_toolbar,
bcrypt,
login_manager,
config,
)

from . import models
from .views.users import users
from .views.activities import activities
from .views.api import api


SQLALCHEMY_DATABASE_URI = "postgres://localhost/stat_tracker"

DEBUG = True
SECRET_KEY = 'SUPERDUPERSECRET'
DEBUG_TB_INTERCEPT_REDIRECTS = False


def create_app():
app = Flask("stat_tracker")
app.config.from_object(__name__)
app.register_blueprint(users)
app.register_blueprint(activities)
app.register_blueprint(api, url_prefix="/api/v1")

config.init_app(app)
db.init_app(app)
#debug_toolbar.init_app(app)
migrate.init_app(app, db)
bcrypt.init_app(app)
login_manager.init_app(app)
login_manager.login_view = "users.login"


return app
Binary file added stat_tracker/__pycache__/__init__.cpython-34.pyc
Binary file not shown.
Binary file added stat_tracker/__pycache__/extensions.cpython-34.pyc
Binary file not shown.
Binary file added stat_tracker/__pycache__/forms.cpython-34.pyc
Binary file not shown.
Binary file added stat_tracker/__pycache__/models.cpython-34.pyc
Binary file not shown.
18 changes: 18 additions & 0 deletions stat_tracker/extensions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
"""Extensions module."""
from flask.ext.sqlalchemy import SQLAlchemy
db = SQLAlchemy()

from flask.ext.migrate import Migrate
migrate = Migrate()

# from flask.ext.debugtoolbar import DebugToolbarExtension
# debug_toolbar = DebugToolbarExtension()

from flask.ext.bcrypt import Bcrypt
bcrypt = Bcrypt()

from flask.ext.login import LoginManager
login_manager = LoginManager()

from flask.ext.appconfig import HerokuConfig
config = HerokuConfig()
Loading