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
74 changes: 74 additions & 0 deletions alembic.ini
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 = sqlite:///dev-db.sqlite


# 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
1 change: 1 addition & 0 deletions alembic/README
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Generic single-database configuration.
81 changes: 81 additions & 0 deletions alembic/env.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@

from helpers.database import Base
from models import notification_model
from models import calendar_model
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)

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


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()
24 changes: 24 additions & 0 deletions alembic/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"}
44 changes: 44 additions & 0 deletions alembic/versions/ed2401b502eb_initial_migration.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
"""Initial Migration

Revision ID: ed2401b502eb
Revises:
Create Date: 2019-05-28 22:52:34.307606

"""
from alembic import op
import sqlalchemy as sa


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


def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('calendars',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('calendar_id', sa.Integer(), nullable=False),
sa.Column('channel_id', sa.String(), nullable=True),
sa.Column('resource_id', sa.String(), nullable=True),
sa.Column('firebase_token', sa.String(), nullable=True),
sa.PrimaryKeyConstraint('id')
)
op.create_table('notification',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('time', sa.String(), nullable=True),
sa.Column('results', sa.String(), nullable=True),
sa.Column('subscriber_info', sa.String(), nullable=True),
sa.Column('platform', sa.String(), nullable=True),
sa.PrimaryKeyConstraint('id')
)
# ### end Alembic commands ###


def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_table('notification')
op.drop_table('calendars')
# ### end Alembic commands ###
2 changes: 1 addition & 1 deletion app.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ def index():

@app.route("/notifications", methods=['POST', 'GET'])
def calendar_notifications():
PushNotification().send_notifications_to_subscribers()
# PushNotification().send_notifications_to_subscribers()
return PushNotification.send_notifications(PushNotification)

@app.route("/channels", methods=['POST', 'GET'])
Expand Down
10 changes: 7 additions & 3 deletions config.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,19 +14,23 @@ class DevelopmentConfig(Config):
DEBUG = True
NOTIFICATION_URL = os.getenv('DEV_NOTIFICATION_URL')
CONVERGE_MRM_URL = os.getenv('DEV_CONVERGE_MRM_URL')
REDIS_DATABASE_URI = os.getenv('DEV_REDIS_URL')
SQLALCHEMY_DATABASE_URI = (
'sqlite:///' + os.path.join(basedir, 'dev-db.sqlite'))


class ProductionConfig(Config):
NOTIFICATION_URL = os.getenv('NOTIFICATION_URL')
CONVERGE_MRM_URL = os.getenv('CONVERGE_MRM_URL')
REDIS_DATABASE_URI = os.getenv('PROD_REDIS_URL')
SQLALCHEMY_DATABASE_URI = (
'sqlite:///' + os.path.join(basedir, 'data.sqlite'))


class TestingConfig(Config):
DEBUG = True
NOTIFICATION_URL = os.getenv('DEV_NOTIFICATION_URL')
CONVERGE_MRM_URL = os.getenv('DEV_CONVERGE_MRM_URL')
REDIS_DATABASE_URI = os.getenv('TEST_REDIS_URL')
SQLALCHEMY_DATABASE_URI = (
'sqlite:///' + os.path.join(basedir, 'test.sqlite'))


config = {
Expand Down
21 changes: 9 additions & 12 deletions helpers/calendar.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,11 @@
from helpers.database import db
# from helpers.database import db


def update_calendar(calendar, calendar_key, room):
if not room['firebaseToken']:
room['firebaseToken'] = ''
if not calendar:
key = len(db.keys('*Calendar*')) + 1
calendar_key = 'Calendar:' + str(key)
elif 'firebase_token' not in calendar.keys() or calendar['firebase_token'] == room['firebaseToken']:
return None

db.hmset(calendar_key, {'calendar_id': room['calendarId'], 'firebase_token': room['firebaseToken']})
db.persist(calendar_key)
# def update_calendar(calendar, calendar_key, room):
# if not room['firebaseToken']:
# room['firebaseToken'] = ''
# if not calendar:
# key = len(db.keys('*Calendar*')) + 1
# db.hmset('Calendar:' + str(key), {'calendar_id': room['calendarId'], 'firebase_token': room['firebaseToken']})
# if 'firebase_token' in calendar.keys() and calendar['firebase_token'] != room['firebaseToken']:
# db.hmset(calendar_key, {'calendar_id': room['calendarId'], 'firebase_token': room['firebaseToken']})
14 changes: 11 additions & 3 deletions helpers/database.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,18 @@
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import scoped_session, sessionmaker
from config import config

import os
import sys
import redis
sys.path.append(os.getcwd())

config_name = os.getenv('APP_SETTINGS')
database_uri = config.get(config_name).REDIS_DATABASE_URI
db = redis.from_url(database_uri, charset="utf-8", decode_responses=True)
database_uri = config.get(config_name).SQLALCHEMY_DATABASE_URI
engine = create_engine(database_uri, convert_unicode=True)
db_session = scoped_session(sessionmaker(autocommit=False,
autoflush=False,
bind=engine))

Base = declarative_base()
Base.query = db_session.query_property()
Empty file added models/__init__.py
Empty file.
13 changes: 13 additions & 0 deletions models/calendar_model.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
from helpers.database import Base
from utilities.utility import Utility
from sqlalchemy import (Column, String, Integer, Sequence)


class Calendar(Base, Utility):
__tablename__ = 'calendars'
id = Column(Integer, Sequence('calendars_id_seq', start=1, increment=1),
primary_key=True)
calendar_id = Column(Integer, nullable=False)
channel_id = Column(String, nullable=True)
resource_id = Column(String, nullable=True)
firebase_token = Column(String, nullable=True)
12 changes: 12 additions & 0 deletions models/notification_model.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
from helpers.database import Base
from utilities.utility import Utility
from sqlalchemy import (Column, String, Integer, Sequence)


class Notification(Base, Utility):
__tablename__ = 'notification'
id = Column(Integer, primary_key=True)
time = Column(String)
results = Column(String)
subscriber_info = Column(String)
platform = Column(String)
Loading