Skip to content

Commit

Permalink
started to refactor flask code and write an app testing framework
Browse files Browse the repository at this point in the history
  • Loading branch information
AJRenold committed Mar 21, 2014
1 parent 9b2a746 commit 50e6979
Show file tree
Hide file tree
Showing 9 changed files with 226 additions and 206 deletions.
Empty file added __init__.py
Empty file.
280 changes: 132 additions & 148 deletions app.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,173 +11,157 @@
logout_user,
user,
)
from models import ( db, Book, Author, Genre, AppUser, stormpathUserHash )

from key import ( apiKey_id, apiKey_secret )
from stormpath.error import Error as StormpathError
from settings import basedir

from models import ( Book, Author, Genre, AppUser, stormpathUserHash )
from core import db

TESTING = True
DEBUG = True
SECRET_KEY = 'my_precious'
# Test User
EMAIL = '[email protected]'
PASSWORD = 'Pass1234'

STORMPATH_API_KEY_ID = apiKey_id
STORMPATH_API_KEY_SECRET = apiKey_secret
STORMPATH_APPLICATION = 'flask-stormpath-sample'

# grabs folder where the script runs
basedir = os.path.abspath(os.path.dirname(__file__))

if TESTING:
DATABASE_PATH = os.path.join(basedir, 'test.db')
else:
# define full path for db
DATABASE_PATH = os.path.join(basedir, DATABASE)

# the database uri
SQLALCHEMY_DATABASE_URI = 'sqlite:///' + DATABASE_PATH

app = Flask(__name__)
app.config.from_object(__name__)
#db = SQLAlchemy(app)
stormpath_manager = StormpathManager(app)
stormpath_manager.login_view = '.login'

@app.context_processor
def inject_appuser():
if user.is_authenticated():
return dict(app_user=AppUser.query.get(stormpathUserHash(user.get_id())))
return dict(app_user=None)

@app.route('/')
def index():
return render_template('index.html')

@app.route('/book/<int:book_id>')
def bookpage(book_id):
if book_id:
book = Book.query.get(book_id)
if book:
#return jsonify(book.as_dict())
return render_template('bookpage.html', book=book)
return redirect(url_for('index'))

@app.route('/author/<author_slug>')
def authorpage(author_slug):
if author_slug:
author = Author.query.filter_by(slug=author_slug).first()
if author:
#return jsonify(author.as_dict())
return render_template('authorpage.html', author=author)
return redirect(url_for('index'))

@app.route('/genre/<genre_slug>')
def genrepage(genre_slug):
if genre_slug:
genre = Genre.query.filter_by(slug=genre_slug).first()
if genre:
#return jsonify(author.as_dict())
return render_template('genrepage.html', genre=genre)
return redirect(url_for('index'))

@app.route('/copyright')
def copyright():
return render_template('copyright.html')

@app.route('/makers')
def makers():
if user.is_authenticated():
return render_template('makers.html')

return render_template('makers.html')

@app.route('/readers')
def readers():
if user.is_authenticated():
return render_template('readers.html')

return render_template('readers.html')
def create_app(config_object):

@app.route('/register', methods=['GET', 'POST'])
def register():
"""
This view allows a user to register for the site.
app = Flask(__name__)
app.config.from_object(config_object)
db.init_app(app)
stormpath_manager = StormpathManager(app)
stormpath_manager.login_view = '.login'

This will create a new User in Stormpath, and then log the user into their
new account immediately (no email verification required).
"""
if request.method == 'GET':
@app.context_processor
def inject_appuser():
if user.is_authenticated():
return redirect(url_for('index'))

return render_template('register.html')

is_author = True if request.form.get('is_author') is not None else False

try:
_user = stormpath_manager.application.accounts.create({
'username': request.form.get('username'),
'email': request.form.get('email'),
'password': request.form.get('password'),
'given_name': request.form.get('first_name'),
'surname': request.form.get('last_name'),
'custom_data': { 'is_author': is_author }
})
_user.__class__ = User

except StormpathError, err:
return render_template('register.html', error=err.message)

login_user(_user, remember=True)
return redirect(url_for('index'))

@app.route('/login', methods=['GET', 'POST'])
def login():
""" User login/auth/session management """
if request.method == 'GET':
user_id = user.get_id()
app_user = AppUser.query.get(stormpathUserHash(user_id))
return dict(app_user=app_user)
return dict(app_user=None)

@app.route('/')
def index():
return render_template('index.html')

@app.route('/book/<int:book_id>')
def bookpage(book_id):
if book_id:
book = Book.query.get(book_id)
if book:
#return jsonify(book.as_dict())
return render_template('bookpage.html', book=book)
return redirect(url_for('index'))

@app.route('/author/<author_slug>')
def authorpage(author_slug):
if author_slug:
author = Author.query.filter_by(slug=author_slug).first()
if author:
#return jsonify(author.as_dict())
return render_template('authorpage.html', author=author)
return redirect(url_for('index'))

@app.route('/genre/<genre_slug>')
def genrepage(genre_slug):
if genre_slug:
genre = Genre.query.filter_by(slug=genre_slug).first()
if genre:
#return jsonify(author.as_dict())
return render_template('genrepage.html', genre=genre)
return redirect(url_for('index'))

@app.route('/copyright')
def copyright():
return render_template('copyright.html')

@app.route('/makers')
def makers():
""" """
if user.is_authenticated():
return redirect(url_for('index'))
return render_template('makers.html')

return render_template('login.html')
return render_template('makers.html')

try:
_user = User.from_login(
request.form.get('email'),
request.form.get('password'),
)
except StormpathError, err:
return render_template('login.html', error=err.message)
@app.route('/readers')
def readers():
if user.is_authenticated():
return render_template('readers.html')

login_user(_user, remember=True)
return redirect(url_for('index'))
return render_template('readers.html')

@app.route('/logout')
@login_required
def logout():
"""User logout/auth/session managment"""
logout_user()
return redirect(url_for('index'))
@app.route('/register', methods=['GET', 'POST'])
def register():
"""
This view allows a user to register for the site.
This will create a new User in Stormpath, and then log the user into their
new account immediately (no email verification required).
"""
if request.method == 'GET':
if user.is_authenticated():
return redirect(url_for('index'))

return render_template('register.html')

is_author = True if request.form.get('is_author') is not None else False

try:
_user = stormpath_manager.application.accounts.create({
'username': request.form.get('username'),
'email': request.form.get('email'),
'password': request.form.get('password'),
'given_name': request.form.get('first_name'),
'surname': request.form.get('last_name'),
'custom_data': { 'is_author': is_author }
})
_user.__class__ = User

except StormpathError, err:
return render_template('register.html', error=err.message)

login_user(_user, remember=True)
return redirect(url_for('index'))

@app.route('/login', methods=['GET', 'POST'])
def login():
""" User login/auth/session management """
if request.method == 'GET':
if user.is_authenticated():
return redirect(url_for('index'))

return render_template('login.html')

try:
_user = User.from_login(
request.form.get('email'),
request.form.get('password'),
)
except StormpathError, err:
return render_template('login.html', error=err.message)

login_user(_user, remember=True)
return redirect(url_for('index'))

@app.route('/logout')
@login_required
def logout():
"""User logout/auth/session managment"""
logout_user()
return redirect(url_for('index'))

return app

if __name__ == "__main__":

db.init_app(app)
app = create_app('core.DevConfig')

args = sys.argv
if args[1] == 'test':
from test.db_create import createTestDB
if not os.path.isfile("test.db"):
print "test.db not found, creating..."
if args[1] == 'dev':
from test.db_create import bootstrapTestDB
if not os.path.isfile("dev.db"):
print "dev.db not found, creating..."
with app.app_context():
createTestDB(db)
else:
os.remove("test.db")
print "Removing test.db and recreating..."
with app.app_context():
createTestDB(db)
db.create_all()
bootstrapTestDB(db)

else:
print 'run app with "$ python app.py test"'
print 'run app with "$ python app.py dev"'
sys.exit()

app.run()
33 changes: 33 additions & 0 deletions core.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import os

from flask.ext.sqlalchemy import SQLAlchemy

from key import ( apiKey_id, apiKey_secret )
from settings import basedir

db = SQLAlchemy()

class Config(object):
DEBUG = False
TESTING = False

class DevConfig(Config):
DEBUG = True
SECRET_KEY = 'my_precious'

STORMPATH_API_KEY_ID = apiKey_id
STORMPATH_API_KEY_SECRET = apiKey_secret
STORMPATH_APPLICATION = 'flask-stormpath-sample'
DATABASE_PATH = os.path.join(basedir, 'dev.db')
SQLALCHEMY_DATABASE_URI = 'sqlite:///' + DATABASE_PATH

class TestConfig(Config):
DEBUG = True
SECRET_KEY = 'my_precious'
TESTING = True

STORMPATH_API_KEY_ID = apiKey_id
STORMPATH_API_KEY_SECRET = apiKey_secret
STORMPATH_APPLICATION = 'flask-stormpath-sample'
DATABASE_PATH = os.path.join(basedir, 'test', 'unittest.db')
SQLALCHEMY_DATABASE_URI = 'sqlite:///' + DATABASE_PATH
4 changes: 1 addition & 3 deletions models.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,7 @@

import re
from unidecode import unidecode
from flask.ext.sqlalchemy import SQLAlchemy

db = SQLAlchemy()
from core import db

class AppUser(db.Model):

Expand Down
4 changes: 4 additions & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,13 @@ Flask==0.10.1
Flask-Login==0.2.9
Flask-SQLAlchemy==1.0
Flask-Stormpath==0.0.1
Flask-Testing==0.4.1
Flask-WTF==0.9.4
Jinja2==2.7.2
MarkupSafe==0.18
SQLAlchemy==0.9.3
Unidecode==0.04.14
WTForms==1.0.5
Werkzeug==0.9.4
itsdangerous==0.23
requests==2.2.1
Expand Down
Loading

0 comments on commit 50e6979

Please sign in to comment.