Skip to content

Commit dd172ac

Browse files
committed
Unify codebase & Add DT
1 parent 6a4a025 commit dd172ac

30 files changed

+1577
-177
lines changed

apps/__init__.py

Lines changed: 1 addition & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -10,43 +10,18 @@
1010
from flask_sqlalchemy import SQLAlchemy
1111
from importlib import import_module
1212

13-
1413
db = SQLAlchemy()
1514
login_manager = LoginManager()
1615

17-
1816
def register_extensions(app):
1917
db.init_app(app)
2018
login_manager.init_app(app)
2119

22-
2320
def register_blueprints(app):
24-
for module_name in ('authentication', 'home'):
21+
for module_name in ('authentication', 'home', 'dyn_dt'):
2522
module = import_module('apps.{}.routes'.format(module_name))
2623
app.register_blueprint(module.blueprint)
2724

28-
29-
def configure_database(app):
30-
31-
@app.before_first_request
32-
def initialize_database():
33-
try:
34-
db.create_all()
35-
except Exception as e:
36-
37-
print('> Error: DBMS Exception: ' + str(e) )
38-
39-
# fallback to SQLite
40-
basedir = os.path.abspath(os.path.dirname(__file__))
41-
app.config['SQLALCHEMY_DATABASE_URI'] = SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(basedir, 'db.sqlite3')
42-
43-
print('> Fallback to SQLite ')
44-
db.create_all()
45-
46-
@app.teardown_request
47-
def shutdown_session(exception=None):
48-
db.session.remove()
49-
5025
from apps.authentication.oauth import github_blueprint
5126

5227
def create_app(config):
@@ -55,5 +30,4 @@ def create_app(config):
5530
register_extensions(app)
5631
register_blueprints(app)
5732
app.register_blueprint(github_blueprint, url_prefix="/login")
58-
configure_database(app)
5933
return app

apps/authentication/decorators.py

Lines changed: 0 additions & 48 deletions
This file was deleted.

apps/authentication/models.py

Lines changed: 35 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414

1515
class Users(db.Model, UserMixin):
1616

17-
__tablename__ = 'Users'
17+
__tablename__ = 'users'
1818

1919
id = db.Column(db.Integer, primary_key=True)
2020
username = db.Column(db.String(64), unique=True)
@@ -27,9 +27,6 @@ class Users(db.Model, UserMixin):
2727

2828
oauth_github = db.Column(db.String(100), nullable=True)
2929

30-
api_token = db.Column(db.String(100))
31-
api_token_ts = db.Column(db.Integer)
32-
3330
def __init__(self, **kwargs):
3431
for property, value in kwargs.items():
3532
# depending on whether value is an iterable or not, we must
@@ -47,19 +44,50 @@ def __init__(self, **kwargs):
4744
def __repr__(self):
4845
return str(self.username)
4946

47+
@classmethod
48+
def find_by_email(cls, email: str) -> "Users":
49+
return cls.query.filter_by(email=email).first()
50+
51+
@classmethod
52+
def find_by_username(cls, username: str) -> "Users":
53+
return cls.query.filter_by(username=username).first()
54+
55+
@classmethod
56+
def find_by_id(cls, _id: int) -> "Users":
57+
return cls.query.filter_by(id=_id).first()
58+
59+
def save(self) -> None:
60+
try:
61+
db.session.add(self)
62+
db.session.commit()
63+
64+
except SQLAlchemyError as e:
65+
db.session.rollback()
66+
db.session.close()
67+
error = str(e.__dict__['orig'])
68+
raise InvalidUsage(error, 422)
69+
70+
def delete_from_db(self) -> None:
71+
try:
72+
db.session.delete(self)
73+
db.session.commit()
74+
except SQLAlchemyError as e:
75+
db.session.rollback()
76+
db.session.close()
77+
error = str(e.__dict__['orig'])
78+
raise InvalidUsage(error, 422)
79+
return
5080

5181
@login_manager.user_loader
5282
def user_loader(id):
5383
return Users.query.filter_by(id=id).first()
5484

55-
5685
@login_manager.request_loader
5786
def request_loader(request):
5887
username = request.form.get('username')
5988
user = Users.query.filter_by(username=username).first()
6089
return user if user else None
6190

6291
class OAuth(OAuthConsumerMixin, db.Model):
63-
user_id = db.Column(db.Integer, db.ForeignKey("Users.id", ondelete="cascade"), nullable=False)
92+
user_id = db.Column(db.Integer, db.ForeignKey("users.id", ondelete="cascade"), nullable=False)
6493
user = db.relationship(Users)
65-

apps/authentication/oauth.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,8 @@
2424
db.session,
2525
user=current_user,
2626
user_required=False,
27-
),
27+
),
28+
2829
)
2930

3031
@oauth_authorized.connect_via(github_blueprint)

apps/authentication/routes.py

Lines changed: 12 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ def login_github():
3030
res = github.get("/user")
3131
return redirect(url_for('home_blueprint.index'))
3232

33+
3334
@blueprint.route('/login', methods=['GET', 'POST'])
3435
def login():
3536
login_form = LoginForm(request.form)
@@ -48,7 +49,7 @@ def login():
4849
user = Users.find_by_email(user_id)
4950

5051
if not user:
51-
return render_template( 'accounts/login.html',
52+
return render_template( 'authentication/login.html',
5253
msg='Unknown User or Email',
5354
form=login_form)
5455

@@ -59,12 +60,12 @@ def login():
5960
return redirect(url_for('home_blueprint.index'))
6061

6162
# Something (user or pass) is not ok
62-
return render_template('accounts/login.html',
63+
return render_template('authentication/login.html',
6364
msg='Wrong user or password',
6465
form=login_form)
6566

6667
if not current_user.is_authenticated:
67-
return render_template('accounts/login.html',
68+
return render_template('authentication/login.html',
6869
form=login_form)
6970
return redirect(url_for('home_blueprint.index'))
7071

@@ -80,15 +81,15 @@ def register():
8081
# Check usename exists
8182
user = Users.query.filter_by(username=username).first()
8283
if user:
83-
return render_template('accounts/register.html',
84+
return render_template('authentication/register.html',
8485
msg='Username already registered',
8586
success=False,
8687
form=create_account_form)
8788

8889
# Check email exists
8990
user = Users.query.filter_by(email=email).first()
9091
if user:
91-
return render_template('accounts/register.html',
92+
return render_template('authentication/register.html',
9293
msg='Email already registered',
9394
success=False,
9495
form=create_account_form)
@@ -101,13 +102,13 @@ def register():
101102
# Delete user from session
102103
logout_user()
103104

104-
return render_template('accounts/register.html',
105+
return render_template('authentication/register.html',
105106
msg='User created successfully.',
106107
success=True,
107108
form=create_account_form)
108109

109110
else:
110-
return render_template('accounts/register.html', form=create_account_form)
111+
return render_template('authentication/register.html', form=create_account_form)
111112

112113

113114
@blueprint.route('/logout')
@@ -116,27 +117,14 @@ def logout():
116117
return redirect(url_for('home_blueprint.index'))
117118

118119
# Errors
120+
119121
@blueprint.context_processor
120-
def is_github():
122+
def has_github():
121123
if Config.GITHUB_ID and Config.GITHUB_SECRET:
122-
return {'is_github': True}
124+
return {'has_github': True}
123125

124-
return {'is_github': False}
126+
return {'has_github': False}
125127

126128
@login_manager.unauthorized_handler
127129
def unauthorized_handler():
128130
return redirect('/login')
129-
130-
# @blueprint.errorhandler(403)
131-
# def access_forbidden(error):
132-
# return render_template('home/page-403.html'), 403
133-
134-
135-
# @blueprint.errorhandler(404)
136-
# def not_found_error(error):
137-
# return render_template('home/page-404.html'), 404
138-
139-
140-
# @blueprint.errorhandler(500)
141-
# def internal_error(error):
142-
# return render_template('home/page-500.html'), 500

apps/authentication/util.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,6 @@
99

1010
# Inspiration -> https://www.vitoshacademy.com/hashing-passwords-in-python/
1111

12-
1312
def hash_pass(password):
1413
"""Hash a password for storing."""
1514

apps/config.py

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,15 +3,28 @@
33
Copyright (c) 2019 - present AppSeed.us
44
"""
55

6-
import os, random, string
6+
import os
77

88
class Config(object):
99

1010
basedir = os.path.abspath(os.path.dirname(__file__))
1111

12+
# for Product model
13+
CURRENCY = { 'usd' : 'usd' , 'eur' : 'eur' }
14+
STATE = { 'completed' : 1 , 'pending' : 2, 'refunded' : 3 }
15+
PAYMENT_TYPE = { 'cc' : 1 , 'paypal' : 2, 'wire' : 3 }
16+
17+
USERS_ROLES = { 'ADMIN' :1 , 'USER' : 2 }
18+
USERS_STATUS = { 'ACTIVE' :1 , 'SUSPENDED' : 2 }
19+
1220
# Assets Management
1321
ASSETS_ROOT = os.getenv('ASSETS_ROOT', '/static/assets')
1422

23+
# celery
24+
CELERY_BROKER_URL = "redis://localhost:6379"
25+
CELERY_RESULT_BACKEND = "redis://localhost:6379"
26+
CELERY_HOSTMACHINE = "celery@app-generator"
27+
1528
# Set up the App SECRET_KEY
1629
SECRET_KEY = os.getenv('SECRET_KEY', 'S3cret_999')
1730

@@ -62,7 +75,11 @@ class Config(object):
6275

6376
# This will create a file in <app> FOLDER
6477
SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(basedir, 'db.sqlite3')
65-
78+
79+
DYNAMIC_DATATB = {
80+
"products": "apps.models.Product"
81+
}
82+
6683
class ProductionConfig(Config):
6784
DEBUG = False
6885

apps/db.sqlite3

12 KB
Binary file not shown.

apps/dyn_dt/__init__.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
# -*- encoding: utf-8 -*-
2+
"""
3+
Copyright (c) 2019 - present AppSeed.us
4+
"""
5+
6+
from flask import Blueprint
7+
8+
blueprint = Blueprint(
9+
'table_blueprint',
10+
__name__,
11+
url_prefix=''
12+
)

0 commit comments

Comments
 (0)