Skip to content

Commit 130a76b

Browse files
committed
adding boilerplate flask code
- adding sqlalchemy - adding postgres support - adding marshmallow - adding flask forms and wtf
1 parent 4ee434a commit 130a76b

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

53 files changed

+1626
-12
lines changed

.gitignore

+2
Original file line numberDiff line numberDiff line change
@@ -94,3 +94,5 @@ ENV/
9494
.idea/
9595
T9WebApp.iml
9696
ubuntu-aws.pem
97+
apvirt/
98+
database/config.properties

application.py

+63-4
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,71 @@
1-
from flask import Flask
1+
from flask import Flask, render_template, request
2+
from database.db import db_session, init_db
3+
import logging
4+
from logging import Formatter, FileHandler
5+
from forms import *
6+
import os
27

38
app = Flask(__name__)
9+
app.secret_key = 's3cr3t'
410

511

6-
@app.route("/")
7-
def hello_world():
8-
return 'Hello World'
12+
@app.teardown_request
13+
def shutdown_session(exception=None):
14+
db_session.remove()
15+
16+
17+
@app.route('/')
18+
def home():
19+
return render_template('pages/placeholder.home.html')
20+
21+
22+
@app.route('/about')
23+
def about():
24+
return render_template('pages/placeholder.about.html')
25+
26+
27+
@app.route('/login')
28+
def login():
29+
form = LoginForm(request.form)
30+
return render_template('forms/login.html', form=form)
31+
32+
33+
@app.route('/register')
34+
def register():
35+
form = RegisterForm(request.form)
36+
return render_template('forms/register.html', form=form)
37+
38+
39+
@app.route('/forgot')
40+
def forgot():
41+
form = ForgotForm(request.form)
42+
return render_template('forms/forgot.html', form=form)
43+
44+
# Error handlers.
45+
46+
47+
@app.errorhandler(500)
48+
def internal_error(error):
49+
#db_session.rollback()
50+
return render_template('errors/500.html'), 500
51+
52+
53+
@app.errorhandler(404)
54+
def not_found_error(error):
55+
return render_template('errors/404.html'), 404
56+
57+
if not app.debug:
58+
file_handler = FileHandler('error.log')
59+
file_handler.setFormatter(
60+
Formatter('%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]')
61+
)
62+
app.logger.setLevel(logging.INFO)
63+
file_handler.setLevel(logging.INFO)
64+
app.logger.addHandler(file_handler)
65+
app.logger.info('errors')
66+
967

1068
if __name__ == "__main__":
69+
init_db()
1170
app.debug = True
1271
app.run()

database/__init__.py

Whitespace-only changes.

database/create_db.py

+28
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
from sqlalchemy import create_engine
2+
3+
4+
# fill out the path to sqlite engine
5+
def get_username(file):
6+
f = open(file)
7+
uname = ""
8+
pword = ""
9+
host = ""
10+
for line in f:
11+
split_str = line.split("=")
12+
if split_str[0] == "username":
13+
uname = split_str[1]
14+
if split_str[0] == "password":
15+
pword = split_str[1]
16+
if split_str[0] == "host":
17+
host = split_str[1]
18+
return [uname, pword, host]
19+
20+
21+
file = "../database/config.properties"
22+
config = get_username(file)
23+
engine = create_engine('postgresql+psycopg2://' + config[0].replace("\n", "") + ':' + config[1].replace("\n", "") +
24+
'@' + config[2].replace("\n", "") + '/postgres')
25+
conn = engine.connect()
26+
conn.execute("commit")
27+
conn.execute("create database t9_db")
28+
conn.close()

database/db.py

+56
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
from sqlalchemy import create_engine
2+
from sqlalchemy.orm import scoped_session, sessionmaker
3+
from sqlalchemy.ext.declarative import declarative_base
4+
import os
5+
from urlparse import urlparse
6+
7+
8+
def get_username(file):
9+
f = open(file)
10+
uname = ""
11+
pword = ""
12+
host = ""
13+
for line in f:
14+
split_str = line.split("=")
15+
if split_str[0] == "username":
16+
uname = split_str[1]
17+
if split_str[0] == "password":
18+
pword = split_str[1]
19+
if split_str[0] == "host":
20+
host = split_str[1]
21+
return [uname, pword, host]
22+
23+
24+
url = None
25+
26+
try:
27+
url = urlparse(os.environ["DATABASE_URL"])
28+
29+
except KeyError:
30+
print("cannot find environment variable")
31+
32+
engine = None
33+
34+
if url:
35+
engine = create_engine('postgresql+psycopg2://' + url.username + ':' + url.password +
36+
'@' + url.hostname + ':' + str(url.port) + '/' + url.path[1:])
37+
else:
38+
file = "./database/config.properties"
39+
config = get_username(file)
40+
engine = create_engine('postgresql+psycopg2://' + config[0].replace("\n", "") + ':' + config[1].replace("\n", "") +
41+
'@' + config[2].replace("\n", "") + '/t9_db')
42+
43+
db_session = scoped_session(sessionmaker(autocommit=False,
44+
autoflush=False,
45+
bind=engine))
46+
47+
Base = declarative_base()
48+
Base.query = db_session.query_property()
49+
50+
51+
def init_db():
52+
# import all modules here that might define models so that
53+
# they will be registered properly on the metadata. Otherwise
54+
# you will have to import them first before calling init_db()
55+
import models
56+
Base.metadata.create_all(bind=engine)

forms.py

+33
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
from flask_wtf import Form
2+
from wtforms import TextField, PasswordField
3+
from wtforms.validators import DataRequired, EqualTo, Length
4+
5+
# Set your classes here.
6+
7+
8+
class RegisterForm(Form):
9+
name = TextField(
10+
'Username', validators=[DataRequired(), Length(min=6, max=25)]
11+
)
12+
email = TextField(
13+
'Email', validators=[DataRequired(), Length(min=6, max=40)]
14+
)
15+
password = PasswordField(
16+
'Password', validators=[DataRequired(), Length(min=6, max=40)]
17+
)
18+
confirm = PasswordField(
19+
'Repeat Password',
20+
[DataRequired(),
21+
EqualTo('password', message='Passwords must match')]
22+
)
23+
24+
25+
class LoginForm(Form):
26+
name = TextField('Username', [DataRequired()])
27+
password = PasswordField('Password', [DataRequired()])
28+
29+
30+
class ForgotForm(Form):
31+
email = TextField(
32+
'Email', validators=[DataRequired(), Length(min=6, max=40)]
33+
)

ma_schema/CompanySchema.py

+8
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
from marshmallow_sqlalchemy import ModelSchema
2+
from models.Company import Company
3+
4+
5+
class CompanySchema(ModelSchema):
6+
class Meta:
7+
model = Company
8+

ma_schema/ReviewSchema.py

+8
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
from marshmallow_sqlalchemy import ModelSchema
2+
from models.Review import Review
3+
4+
5+
class ReviewSchema(ModelSchema):
6+
class Meta:
7+
model = Review
8+

ma_schema/UserSchema.py

+8
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
from marshmallow_sqlalchemy import ModelSchema
2+
from models.User import User
3+
4+
5+
class UserSchema(ModelSchema):
6+
class Meta:
7+
model = User
8+

ma_schema/__init__.py

Whitespace-only changes.

models/Company.py

+14
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
from database.db import Base
2+
from sqlalchemy import Column, String, Integer
3+
from sqlalchemy.orm import relationship
4+
5+
6+
class Company(Base):
7+
__tablename__ = 'Companies'
8+
id = Column(String, primary_key=True)
9+
name = Column(String(100))
10+
r_cnt = Column(Integer)
11+
reviews = relationship("Company")
12+
13+
def __repr__(self):
14+
return "<Company:" + self.id + " " + self.name + ">"

models/Review.py

+17
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
from sqlalchemy import ForeignKey
2+
from database.db import Base
3+
from sqlalchemy import Column, String
4+
from sqlalchemy.orm import relationship
5+
6+
7+
class Review(Base):
8+
__tablename__ = 'Reviews'
9+
id = Column(String, primary_key=True)
10+
user_id = Column(String(100), ForeignKey("User.id"), nullable=False)
11+
company_id = Column(String(100), ForeignKey("Company.id"), nullable=False)
12+
content = Column(String(100))
13+
user = relationship("User", ForeignKey("User.id"))
14+
company = relationship("Company", ForeignKey("Company.id"))
15+
16+
def __repr__(self):
17+
return "<Review:" + self.id + " " + self.content + ">"

models/User.py

+15
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
from database.db import Base
2+
from sqlalchemy import Column, String
3+
from sqlalchemy.orm import relationship
4+
5+
6+
class User(Base):
7+
__tablename__ = 'Users'
8+
9+
id = Column(String, primary_key=True)
10+
name = Column(String(120))
11+
reviews = relationship("Review")
12+
13+
def __repr__(self):
14+
return "<User:" + self.id + " " + self.name + ">"
15+

models/__init__.py

Whitespace-only changes.

requirements.txt

+18-8
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,19 @@
1-
appdirs==1.4.1
1+
Fabric==1.8.2
22
Flask==0.10.1
3-
itsdangerous==0.24
4-
Jinja2==2.9.5
5-
MarkupSafe==0.23
6-
packaging==16.8
7-
pyparsing==2.1.10
8-
six==1.10.0
9-
Werkzeug==0.11.15
3+
Flask-SQLAlchemy==1.0
4+
Flask-WTF==0.9.4
5+
Jinja2==2.7.2
6+
MarkupSafe==0.18
7+
SQLAlchemy==0.9.3
8+
WTForms==1.0.5
9+
Werkzeug==0.9.4
10+
coverage==3.7.1
11+
ecdsa==0.10
12+
gunicorn==19.3.0
13+
itsdangerous==0.23
14+
paramiko==1.12.2
15+
pycrypto==2.6.1
16+
wsgiref==0.1.2
17+
psycopg2==2.6.2
18+
marshmallow-sqlalchemy
19+
flask-marshmallow

static/css/bootstrap-3.1.1.min.css

+7
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)