Skip to content

Commit 5e8dc66

Browse files
committed
Minor refactor.
1 parent 44e16ad commit 5e8dc66

File tree

22 files changed

+144
-99
lines changed

22 files changed

+144
-99
lines changed

.env.example

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,14 @@
11
ENVIRONMENT=production
2-
FLASK_APP=main.py
32
FLASK_DEBUG=True
4-
SECRET_KEY=HGFDGGUFCJHDJCWDGCKDWWW
3+
SECRET_KEY=YourSecretKey
54

65
REDIS_URI=redis://:password@host.com:1234
76

87
SQLALCHEMY_DATABASE_URI=mysql+pymysql://myuser:mypassword@host.example.com:1234/mydatabase
9-
SQLALCHEMY_TRACK_MODIFICATIONS=False
108
SQLALCHEMY_CA_CERTS="./certificate.crt"
9+
SQLALCHEMY_TRACK_MODIFICATIONS=False
10+
SQLALCHEMY_ECHO=False
1111

1212
ASSETS_DEBUG=False
1313
LESS_RUN_IN_DEBUG=False
14-
COMPRESSOR_DEBUG=False
15-
ASSETS_DEBUG=False
16-
LESS_RUN_IN_DEBUG=False
14+
COMPRESSOR_DEBUG=False

.flake8

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
[flake8]
2+
select = E9,F63,F7,F82
3+
exclude = .git,.github,__pycache__,.pytest_cache,.venv,logs,creds

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,7 @@ ENV/
8989
env.bak/
9090
venv.bak/
9191
.creds/
92+
.creds
9293

9394
# Spyder project settings
9495
.spyderproject

Makefile

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -86,5 +86,5 @@ clean:
8686
find . -type d -wholename '**/.pytest_cache' -exec rm -rf {} + && \
8787
find . -type d -wholename '**/*.log' -exec rm -rf {} + && \
8888
find . -type d -wholename './.reports/*' -exec rm -rf {} + && \
89-
find . -type d -wholename '**/.webassets-cache' -exec rm -rf {} +
89+
find . -type d -wholename '**/.webassets-cache' -exec rm -rf {}
9090

README.md

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18,15 +18,16 @@
1818

1919
Get set up locally in two steps:
2020

21-
### Environment Variables
21+
### Configure
2222

2323
Replace the values in **.env.example** with your values and rename this file to **.env**:
2424

25+
* `ENVIRONMENT`: Enable (`development` or `production`).
2526
* `FLASK_APP`: Entry point of your application; should be `main.py`.
2627
* `FLASK_DEBUG`: Toggle debug mode on (`True`) or off (`False`).
2728
* `SECRET_KEY`: Randomly generated string of characters used to encrypt your app's data.
28-
* `SQLALCHEMY_DATABASE_URI`: Connection URI of a SQL database.
29-
* `SESSION_REDIS`: Connection URI of a Redis instance.
29+
* `SQLALCHEMY_DATABASE_URI`: Connection URI of a SQL database (ie: `mysql+pymysql://myuser:mypassword@host.example.com:1234/mydatabase`)
30+
* `REDIS_URI`: Connection URI of a Redis instance (ie: `redis://:password@host.com:1234`)
3031
* `LESS_BIN` *(optional for static assets)*: Path to your local LESS installation via `which lessc`.
3132
* `ASSETS_DEBUG` *(optional)*: Debug asset creation and bundling in `development`.
3233
* `LESS_RUN_IN_DEBUG` *(optional)*: Debug LESS while in `development`.

config.py

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,9 @@ class Config:
1313

1414
# General Config
1515
ENVIRONMENT = environ.get("ENVIRONMENT")
16-
FLASK_APP = environ.get("FLASK_APP")
16+
17+
# Flask Config
18+
FLASK_APP = "main.py"
1719
FLASK_DEBUG = environ.get("FLASK_DEBUG")
1820
SECRET_KEY = environ.get("SECRET_KEY")
1921

@@ -30,9 +32,9 @@ class Config:
3032
# Static Assets
3133
STATIC_FOLDER = "static"
3234
TEMPLATES_FOLDER = "templates"
33-
COMPRESSOR_DEBUG = True
35+
COMPRESSOR_DEBUG = environ.get("COMPRESSOR_DEBUG")
3436

3537
# Flask-SQLAlchemy
3638
SQLALCHEMY_DATABASE_URI = environ.get("SQLALCHEMY_DATABASE_URI")
37-
SQLALCHEMY_TRACK_MODIFICATIONS = False
38-
SQLALCHEMY_ECHO = False
39+
SQLALCHEMY_TRACK_MODIFICATIONS = environ.get("SQLALCHEMY_TRACK_MODIFICATIONS")
40+
SQLALCHEMY_ECHO = environ.get("SQLALCHEMY_ECHO")

flask_session_tutorial/__init__.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,14 +23,14 @@ def create_app():
2323

2424
with app.app_context():
2525
from . import auth
26-
from .assets import compile_auth_assets, compile_static_assets
26+
from .assets import compile_static_assets, compile_stylesheet_assets
2727

2828
app.register_blueprint(main.main)
2929
app.register_blueprint(auth.auth)
3030

3131
# Create static asset bundles
3232
compile_static_assets(app)
33-
compile_auth_assets(app)
33+
compile_stylesheet_assets(app)
3434

3535
# Create Database Models
3636
db.create_all()

flask_session_tutorial/assets.py

Lines changed: 36 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,50 +1,62 @@
11
"""Compile static asset bundles."""
2+
from flask import Flask
23
from flask_assets import Bundle, Environment
34

45

5-
def compile_auth_assets(app):
6-
"""Generate static assets for the auth views."""
6+
def compile_stylesheet_assets(app: Flask):
7+
"""
8+
Generate stylesheets for thr application.
9+
10+
:param Flask app: Parent application to generate styles for.
11+
"""
712
assets = Environment(app)
813
Environment.auto_build = True
914
Environment.debug = False
1015
# Stylesheets Bundle
11-
less_bundle = Bundle(
16+
stylesheet_bundle_account = Bundle(
1217
"src/less/account.less",
1318
filters="less,cssmin",
1419
output="dist/css/account.css",
1520
extra={"rel": "stylesheet/less"},
1621
)
17-
# JavaScript Bundle
18-
js_bundle = Bundle("src/js/main.js", filters="jsmin", output="dist/js/main.min.js")
22+
stylesheet_bundle_dashboard = Bundle(
23+
"src/less/dashboard.less",
24+
filters="less,cssmin",
25+
output="dist/css/dashboard.css",
26+
extra={"rel": "stylesheet/less"},
27+
)
1928
# Register assets
20-
assets.register("less_all", less_bundle)
21-
assets.register("js_all", js_bundle)
29+
assets.register("styles_account", stylesheet_bundle_account)
30+
assets.register("styles_dashboard", stylesheet_bundle_dashboard)
2231
# Build assets in development mode
2332
if app.config.get("ENVIRONMENT") != "production":
24-
less_bundle.build(force=True)
25-
js_bundle.build()
33+
stylesheet_bundle_account.build(force=True)
34+
stylesheet_bundle_dashboard.build(force=True)
35+
2636

37+
def compile_javascript_assets(app: Flask):
38+
"""
39+
Generate static assets for main views.
2740
28-
def compile_main_assets(app):
29-
"""Generate static assets for main views."""
41+
:param Flask app: Parent Flask application to generate Javascript bundles for.
42+
"""
3043
assets = Environment(app)
3144
Environment.auto_build = True
3245
Environment.debug = False
33-
# Stylesheets Bundle
34-
less_bundle = Bundle(
35-
"src/less/dashboard.less",
36-
filters="less,cssmin",
37-
output="dist/css/dashboard.css",
38-
extra={"rel": "stylesheet/less"},
39-
)
46+
# JavaScript Bundle
47+
js_bundle = Bundle("src/js/main.js", filters="jsmin", output="dist/js/main.min.js")
4048
# Register assets
41-
assets.register("less_all", less_bundle)
49+
assets.register("js_all", js_bundle)
4250
# Build assets in development mode
4351
if app.config.get("ENVIRONMENT") != "production":
44-
less_bundle.build(force=True)
52+
js_bundle.build(force=True)
53+
4554

55+
def compile_static_assets(app: Flask):
56+
"""
57+
Compile all asset bundles.
4658
47-
def compile_static_assets(app):
48-
"""Compile all asset bundles."""
49-
compile_auth_assets(app)
50-
compile_main_assets(app)
59+
:param Flask app: Parent Flask application to generate asset bundles for.
60+
"""
61+
compile_stylesheet_assets(app)
62+
compile_javascript_assets(app)

flask_session_tutorial/auth.py

Lines changed: 21 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
"""Routes for user authentication."""
2-
from flask import Blueprint, flash, redirect, render_template, request, url_for
2+
from typing import Optional
3+
4+
from flask import Blueprint, Response, flash, redirect, render_template, request, url_for
35
from flask_login import current_user, login_user
46

57
from flask_session_tutorial import login_manager
@@ -11,9 +13,10 @@
1113

1214

1315
@auth.route("/signup", methods=["GET", "POST"])
14-
def signup():
16+
def signup() -> Response:
1517
"""
1618
Sign-up form to create new user accounts.
19+
1720
GET: Serve sign-up page.
1821
POST: Validate form, create account, redirect user to dashboard.
1922
"""
@@ -39,15 +42,15 @@ def signup():
3942

4043

4144
@auth.route("/login", methods=["GET", "POST"])
42-
def login():
45+
def login() -> Response:
4346
"""
4447
Log-in page for registered users.
48+
4549
GET: Serve Log-in page.
4650
POST: Validate form and redirect user to dashboard.
4751
"""
4852
if current_user.is_authenticated:
4953
return redirect(url_for("main.dashboard")) # Bypass if user is logged in
50-
5154
form = LoginForm()
5255
if form.validate_on_submit():
5356
user = User.query.filter_by(email=form.email.data).first() # Validate Login Attempt
@@ -67,15 +70,25 @@ def login():
6770

6871

6972
@login_manager.user_loader
70-
def load_user(user_id):
71-
"""Check if user is logged-in upon page load."""
73+
def load_user(user_id: int) -> Optional[User]:
74+
"""
75+
Check if user is logged-in upon page load.
76+
77+
:param int user_id: Primary user ID to load from database, if exists.
78+
79+
:returns: Optional[User]
80+
"""
7281
if user_id is not None:
7382
return User.query.get(user_id)
7483
return None
7584

7685

7786
@login_manager.unauthorized_handler
78-
def unauthorized():
79-
"""Redirect unauthorized users to Login page."""
87+
def unauthorized() -> Response:
88+
"""
89+
Redirect unauthorized users to Login page.
90+
91+
:returns: Response
92+
"""
8093
flash("You must be logged in to view that page.")
8194
return redirect(url_for("auth.login"))

flask_session_tutorial/forms.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -7,35 +7,35 @@
77
class SignupForm(FlaskForm):
88
"""User Sign-up Form."""
99

10-
name = StringField("Name", validators=[DataRequired()])
11-
email = StringField(
10+
user_name = StringField("Name", validators=[DataRequired()])
11+
user_email = StringField(
1212
"Email",
1313
validators=[
1414
Length(min=6),
1515
Email(message="Enter a valid email."),
1616
DataRequired(),
1717
],
1818
)
19-
password = PasswordField(
19+
user_password = PasswordField(
2020
"Password",
2121
validators=[
2222
DataRequired(),
2323
Length(min=6, message="Select a stronger password."),
2424
],
2525
)
26-
confirm = PasswordField(
26+
user_password_confirm = PasswordField(
2727
"Confirm Your Password",
2828
validators=[
2929
DataRequired(),
3030
EqualTo("password", message="Passwords must match."),
3131
],
3232
)
33-
website = StringField("Website", validators=[Optional()])
34-
submit = SubmitField("Register")
33+
user_metadata_website = StringField("Website", validators=[Optional()])
34+
submit_button = SubmitField("Register")
3535

3636

3737
class LoginForm(FlaskForm):
38-
"""User Log-in Form."""
38+
"""User Log-in Form for existing users."""
3939

4040
email = StringField("Email", validators=[DataRequired(), Email(message="Enter a valid email.")])
4141
password = PasswordField("Password", validators=[DataRequired()])

0 commit comments

Comments
 (0)