Skip to content

Commit

Permalink
Merge pull request #10 from DeepBlockDeepak/add-config-file
Browse files Browse the repository at this point in the history
Add config file
  • Loading branch information
DeepBlockDeepak authored Nov 23, 2023
2 parents 2b04942 + e01a0d9 commit 05d08cb
Show file tree
Hide file tree
Showing 8 changed files with 117 additions and 81 deletions.
3 changes: 3 additions & 0 deletions database.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()
66 changes: 26 additions & 40 deletions main.py
Original file line number Diff line number Diff line change
@@ -1,50 +1,36 @@
import os

from flask import Flask, render_template
from flask import Flask
from flask_login import LoginManager
from flask_sqlalchemy import SQLAlchemy

# attempting to create/read/write the .db in the top project directory, whether on replit or local
cwd = os.getcwd()


# use the following as a second paramter to dictate where you want the database to exist. Default is /instance
# ,instance_path='/home/runner/computroniumflaskapp'
app = Flask(__name__, instance_path=cwd)
from src.config import Config
from database import db # import the db instance
from src.views import welcome_page, not_found

# create login_manager and initialize login_manager here:
login_manager = LoginManager()
login_manager.init_app(app)
# testing to see whether unlogged in viewers are auto-sent to the register page
# @BUG -> This auto-routing to /register doesn't work
login_manager.login_view = "register"

# set the SQLALCHEMY_DATABASE_URI key
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///travel_library.db"
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
app.config["SECRET_KEY"] = "i-dont-know"
# create an SQLAlchemy object named `db` and bind it to your app
db = SQLAlchemy(app)
def create_app():
# Initialize Flask app
app = Flask(__name__)
app.config.from_object(Config) # Load configuration from config.py

# Initialize SQLAlchemy with the app
db.init_app(app)

# a simple initial greeting
@app.route("/")
@app.route("/index")
@app.route("/home")
def welcome_page():
# render a login page before entering this page!
return render_template("welcome_page.html")
# Initialize Flask-Login manager
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = "login" # Specify the route for unauthenticated users

# Load user function for Flask-Login
from src.models import User

# app name
@app.errorhandler(404)
def not_found(e): # is this var, e, needed?
return render_template("404.html")
@login_manager.user_loader
def load_user(user_id):
return User.query.get(int(user_id))

# Register blueprints, routes, and error handlers
app.add_url_rule("/", "welcome_page", welcome_page)
app.add_url_rule("/index", "welcome_page", welcome_page)
app.add_url_rule("/home", "welcome_page", welcome_page)

# I still don't get why routes must be imported here!!!
from src.routes import *
# Register error handlers
app.register_error_handler(404, not_found)

# Need to use this boiler plate so that other functions can be tested in Shell without triggering the Flask App to run
if __name__ == "__main__":
app.run(host="0.0.0.0", port=81)
return app
6 changes: 6 additions & 0 deletions run.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
from main import create_app

app = create_app()

if __name__ == "__main__":
app.run()
32 changes: 32 additions & 0 deletions src/config.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import os


class Config:
"""Base configuration."""

# Default secret key
SECRET_KEY = os.getenv("SECRET_KEY", "your-default-secret-key")

# Default SQLAlchemy settings
SQLALCHEMY_DATABASE_URI = os.getenv("DATABASE_URL", "sqlite:///travel_library.db")
SQLALCHEMY_TRACK_MODIFICATIONS = False


class DevelopmentConfig(Config):
"""Development configuration."""

DEBUG = True
SQLALCHEMY_ECHO = True # If you want to see SQLAlchemy queries in the logs


class TestingConfig(Config):
"""Testing configuration."""

TESTING = True
SQLALCHEMY_DATABASE_URI = "sqlite:///:memory:" # Use in-memory SQLite for tests


class ProductionConfig(Config):
"""Production configuration."""

DEBUG = False
2 changes: 1 addition & 1 deletion src/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
from flask_login import UserMixin
from werkzeug.security import check_password_hash, generate_password_hash

from main import db
from database import db


# Allows a User to write a "tweet" on the Dashboard
Expand Down
74 changes: 35 additions & 39 deletions src/routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@
from flask import flash, redirect, render_template, request, session, url_for
from flask_login import current_user, login_required, login_user, logout_user

from main import app, db
from main import app # @ BUG: Deprecated!!!
from database import db
from src.chat_gpt_tools.gpt import SumChatGPT
from src.forms import (
BudgetForm,
Expand Down Expand Up @@ -42,39 +43,46 @@
CURRENT_SESSION_USER = "current_session_user"


# handles the user login
def authenticate_user(email, password):
"""
Authenticate a user by email and password.
Args:
email (str): User's email address.
password (str): User's password.
Returns:
User: Authenticated user object, or None if authentication fails.
"""
user = User.query.filter_by(email=email).first()
if user and user.check_password(password):
return user
return None


@app.route("/login", methods=["GET", "POST"])
def login():
# immediately check if the user is logged in, and if so, redirect them
# Redirect already authenticated users to the home page
if current_user.is_authenticated:
flash("You must logout before you can log back in.")
return render_template("welcome_page.html")
flash("You are already logged in.")
return redirect(url_for("welcome_page"))

# make a login form
# Create and process the login form
form = LoginForm(csrf_enabled=False)

if form.validate_on_submit():
# find the user based on their sign-in email
user = User.query.filter_by(email=form.email.data).first()

# check for bad log-ins, notifying the user
if user is None or not user.check_password(form.password.data):
flash("You used an invalid username or invalid password")
return redirect(url_for("login"))

# log the verified user into the app, and store them into the session
login_user(user, remember=form.remember.data)
session[CURRENT_SESSION_USER] = user.id

# not sure how to use this yet
# next_page = request.args.get('next')
# Authenticate user
user = authenticate_user(form.email.data, form.password.data)
if user:
# Login user and set session variable
login_user(user, remember=form.remember.data)
session[CURRENT_SESSION_USER] = user.id

# Redirect to the requested page or to the user's profile
next_page = request.args.get("next")
flash(f"Welcome back, {user.username}!")
return redirect(next_page or url_for("profile", user_id=user.id))
flash("Invalid username or password.")

# redirect the valid login to the profiles page
# return redirect(next_page) if next_page else redirect(url_for('profiles', _external=True, _scheme='http'))
flash(f"Successful login, {user.username}.")
return redirect(url_for("profile", user_id=user.id))

# if a failed form attempt occurred
return render_template("login.html", form=form)


Expand All @@ -94,18 +102,6 @@ def logout():
return render_template("welcome_page.html")


# OLD PLACE_INFO ROUTE
# Renders page detailing the Place()
# used for anchoring Place items within html
# @app.route("/place_info/<int:place_id>")
# @login_required
# def place_info(place_id):
# get the unique place by id
# place = Place.query.get(place_id)

# return render_template('place.html', place=place)


# Renders page detailing the Place()
# used for anchoring Place items within html
@app.route("/place_info/<int:place_id>", methods=["POST", "GET"])
Expand Down
2 changes: 1 addition & 1 deletion src/routing_helper_functions.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

import json

from main import db
from database import db
from src.log_manager import global_logger as log
from src.map_requests import APIError, get_nearby_activities, get_route_distance_meters
from src.models import Favoriteitem, Place, Searchitem, Searchlist, User
Expand Down
13 changes: 13 additions & 0 deletions src/views.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
from flask import render_template


# Define route for the homepage
def welcome_page():
# Render the welcome page template
return render_template("welcome_page.html")


# Define custom error handler for 404 errors
def not_found(_): # Unused error argument can be indicated with an underscore
# Render the 404 error page template
return render_template("404.html")

0 comments on commit 05d08cb

Please sign in to comment.