Skip to content

Commit

Permalink
Added sample users_dev db and User model to init the postgres databas…
Browse files Browse the repository at this point in the history
…e, added script to load couple of entries in users table
  • Loading branch information
mrsan22 committed Jun 8, 2018
1 parent 07185bc commit ee2bcd9
Show file tree
Hide file tree
Showing 5 changed files with 156 additions and 2 deletions.
2 changes: 1 addition & 1 deletion .env
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,6 @@ APP_DEV_SETTINGS=server.settings.DevelopmentConfig
APP_TEST_SETTINGS=server.settings.TestingConfig
POSTGRES_USER=postgres
POSTGRES_PASSWORD=postgres
DB_NAME=test_db
DB_NAME=users_dev
DB_SERVICE=postgres
DB_PORT=5432
2 changes: 1 addition & 1 deletion postgresql/init.sql
Original file line number Diff line number Diff line change
@@ -1 +1 @@
CREATE DATABASE test_db;
CREATE DATABASE users_dev;
19 changes: 19 additions & 0 deletions server/entrypoint.sh
Original file line number Diff line number Diff line change
@@ -1,3 +1,22 @@
#!/bin/sh

# Below shells script is required because the flask container need to wait for postgres db server to startup before
# accessing it below.

RETRIES=5
USER=postgres
DATABASE=users_dev
HOST=postgres

until psql -h $HOST -U $USER -d $DATABASE -c "select 1" > /dev/null 2>&1 || [ $RETRIES -eq 0 ]; do
echo "Waiting for postgres server to start, $((RETRIES)) remaining attempts..."
RETRIES=$((RETRIES-=1))
sleep 1
done

echo "PostgreSQL started!"

# Run below commands from manage.py to initialize db and have some default data.
python manage.py recreate_db
python manage.py seed_db
uwsgi --ini /etc/uwsgi.ini
50 changes: 50 additions & 0 deletions server/main/models/user.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
# -*- coding: utf-8 -*-

from datetime import datetime

from server.main import db
from sqlalchemy.sql import func


class BaseModel(db.Model):
"""Base data model for all objects"""
__abstract__ = True

def __init__(self, *args):
super().__init__(*args)

def __repr__(self):
"""Define a base way to print models"""
return '%s(%s)' % (self.__class__.__name__, {
column: value
for column, value in self._to_dict().items()
})

def json(self):
"""
Define a base way to jsonify models, dealing with datetime objects
"""
return {
column: value if not isinstance(value, datetime.date) else value.strftime('%Y-%m-%d')
for column, value in self._to_dict().items()
}


class User(BaseModel, db.Model):
"""Model for users table"""
__tablename__ = "users"

id = db.Column(db.Integer, primary_key=True, autoincrement=True)
username = db.Column(db.String(128), nullable=False)
email = db.Column(db.String(128), nullable=False)
password = db.Column(db.String(128), nullable=False)
active = db.Column(db.Boolean(), default=True, nullable=False)
# using func.now(), so time is calculated by the DB server and not by app server.
# https://stackoverflow.com/questions/13370317/sqlalchemy-default-datetime?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa
created_date = db.Column(db.DateTime, nullable=False, default=func.now())

def __init__(self, username, email, password):
super().__init__()
self.username = username
self.email = email
self.password = password
85 changes: 85 additions & 0 deletions server/manage.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
"""
Test Suite for Flask.
To run:
python test_suite test
python test_suite cov
"""

import unittest
from coverage import coverage
from flask_script import Manager

from server.main import db
from server.main.api import create_app_blueprint
from server.main.models.user import User

COV = coverage(
branch=True,
include='main/*',
omit=[
'tests/*',
'wsgi.py',
'settings.py',
'__init__.py',
'main/*/__init__.py'
'main/static/*'
'main/templates/*'
'main/import_policy/*'
'main/models/*'
]
)

COV.start()

# create flask application instance
app = create_app_blueprint('development')
manager = Manager(app)


@manager.command
def test():
"""Runs the unit tests without test coverage."""
test_suite = unittest.TestLoader().discover('tests', pattern='test*.py')
result = unittest.TextTestRunner(verbosity=2).run(test_suite)
if result.wasSuccessful():
return 0
return 1

@manager.command
def cov():
"""Runs the unit tests with coverage."""
tests = unittest.TestLoader().discover('tests', pattern='test*.py')
result = unittest.TextTestRunner(verbosity=2).run(tests)
if result.wasSuccessful():
COV.stop()
COV.save()
print('Coverage Summary:')
COV.report()
COV.html_report(directory='tests/coverage')
COV.erase()
return 0
return 1

@manager.command
def recreate_db():
db.drop_all()
db.create_all()
db.session.commit()

@manager.command
def seed_db():
"""Seed the user table in test_db database."""
db.session.add(User(
username='sanjiv',
email='mr.san.kumar@gmail.com',
password='sanjiv'
))
db.session.add(User(
username='admin',
email='admin@gmail.com',
password='admin'
))
db.session.commit()

if __name__ == '__main__':
manager.run()

0 comments on commit ee2bcd9

Please sign in to comment.