Skip to content

Commit

Permalink
updated db connection
Browse files Browse the repository at this point in the history
  • Loading branch information
zepor committed Dec 26, 2023
1 parent 6f44da6 commit 3fd5c32
Show file tree
Hide file tree
Showing 9 changed files with 65 additions and 81 deletions.
26 changes: 12 additions & 14 deletions backend-container/flaskapp/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,37 +59,35 @@
from src.nflfeapi.populateseasons import populate_seasons, bp_populate_seasons
from src.nflfeapi.populateteams import populate_teams, bp_populate_teams
from src.nflfeapi.support_api import submit_support_request, bp_support_api

#ROUTERS IMPORTS

#UTILS IMPORTS
from src.utils.auth import auth_blueprint, init_oauth
from src.utils.auth import init_oauth, auth_blueprint, login, callback, logout, home
from src.utils.log import be_logger
from src.utils.logandcatchexceptions import log_and_catch_exceptions
from src.utils.notfound import init_app

from config import (Config, DevelopmentConfig, ProductionConfig)
from flask import Flask, jsonify, request, session, redirect, url_for, render_template, make_response
from flask import Flask
from flask_cors import CORS
from flask_mongoengine import MongoEngine
from dotenv import load_dotenv
import logging
import json
from os import environ as env
import sys
import os
import os.path
load_dotenv()
sys.path.append('/ssweb')
sys.path.append('/ssweb/src')
app = Flask(__name__)
app = Flask(__name__, template_folder='../templates')

init_oauth(app)
CORS(app, origins=['https://0.0.0.0', 'https://loveoffootball.io', 'http://localhost:3000'], resources={r"/api/*": {"origins": "*"}})
CORS(app, origins=['https://0.0.0.0', 'https://loveoffootball.io', 'http://localhost:3000', 'http://localhost:5000'], resources={r"/api/*": {"origins": "*"}})
mongodb_client = get_mongodb_connection()
db = MongoEngine(app)
redis_primary_host = 'redis' # The host used in the development environment
redis_primary_host = 'redis'
redis_fallback_host = 'redis-service'
redis_port = 6379 # Default Redis port
redis_port = 6379
r = connect_to_redis(redis_primary_host, redis_fallback_host, redis_port)
data_cache = FootballData()
app.debug = True
Expand All @@ -111,27 +109,27 @@
app.register_blueprint(bp_seasons)
app.register_blueprint(bp_seasonal_stats)
app.register_blueprint(bp_pbp, url_prefix='/pbp')
app.register_blueprint(auth_blueprint, url_prefix="/auth")
app.register_blueprint(auth_blueprint, url_prefix='/auth')
app.register_blueprint(bp_default)
app.register_blueprint(bp_get_data)
app.register_blueprint(bp_live_games)
app.register_blueprint(bp_get_top10)
app.register_blueprint(bp_venues)
app.register_blueprint(bp_populate_seasons)
app.register_blueprint(bp_populate_teams)
app.register_blueprint(bp_support_api)
app.register_blueprint(bp_support_api, url_prefix="/api")
app.secret_key = 'sessionkey'
app.jinja_env.cache = {}

logger = logging.getLogger(__name__)
FLASK_DEBUG = os.environ.get('FLASK_DEBUG')
be_logger.info(f"Current FLASK_DEBUG: {FLASK_DEBUG}")
if __name__ == "__main__":
clear_cache()
#clear_cache()
if FLASK_DEBUG == 'true' and os.environ.get('WERKZEUG_RUN_MAIN') == 'true':
data = data or FootballData()
data = FootballData()
app.run(host='0.0.0.0', port=5000, debug=True, use_reloader=True)
elif FLASK_DEBUG != 'true':
# In production mode, just initialize as usual
data = data or FootballData()
data = FootballData()
app.run()
38 changes: 15 additions & 23 deletions backend-container/src/database/connections.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import os
from src.utils.log import be_logger
import redis
from pymongo import MongoClient
from pymongo.errors import ConnectionFailure
import redis
from dotenv import load_dotenv
from src.utils.log import be_logger
load_dotenv()
def get_mongodb_connection():
"""Establishes a connection to MongoDB.
Expand All @@ -15,29 +15,21 @@ def get_mongodb_connection():
ConnectionFailure: If the connection to MongoDB fails after the maximum number of retries.
"""
mongodb_service_name = os.getenv('MONGODB_SERVICE_NAME', 'localhost')
mongodb_url = os.getenv(
'MONGODB_URL', f"mongodb://{mongodb_service_name}:27017/current_season"
)
MAX_RETRIES = 5 # Maximum number of retries
RETRY_DELAY = 5
try:
mongodb_url = os.environ.get('MONGODB_URL')
if not mongodb_url:
raise ValueError("MONGODB_URL environment variable not set.")

client = MongoClient(mongodb_url, connectTimeoutMS=30000, socketTimeoutMS=None)
client = MongoClient(mongodb_url, serverSelectionTimeoutMS=5000, connect=False,
maxPoolSize=10, connectTimeoutMS=30000, retryWrites=True,
w='majority', retryReads=True)

for attempt in range(1, MAX_RETRIES + 1):
try:
client.admin.command('ismaster')
return client # Return the client object if the connection is successful
except ConnectionFailure:
if attempt < MAX_RETRIES:
logging.warning(f"MongoDB server not available. "
f"Attempt {attempt} of {MAX_RETRIES}. "
f"Retrying in {RETRY_DELAY} seconds...")
time.sleep(RETRY_DELAY) # Wait for a while before retrying
else:
logging.error("MongoDB server not available after maximum retries.")
# Handle the maximum retries reached scenario
return None # Return None to indicate a failure
client.admin.command('ping') # Test the connection
be_logger.debug("Successfully connected to MongoDB.")
return client
except Exception as e:
be_logger.error(f"Failed to connect to MongoDB: {e}")
return None

def connect_to_redis(primary_host, fallback_host, port=6379):
"""Establishes a connection to Redis.
Expand Down
4 changes: 2 additions & 2 deletions backend-container/src/nflfeapi/default.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,8 @@


@log_and_catch_exceptions
@bp_default.route('/', defaults={'path': ''})
@bp_default.route('/<path:path>')
#@bp_default.route('/99', defaults={'path': ''})
@bp_default.route('/99<path:path>')
def serve(path):
try:
be_logger.info("Fetching live games data...")
Expand Down
42 changes: 15 additions & 27 deletions backend-container/src/nflfeapi/support_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,61 +8,49 @@
from datetime import datetime
from flask_cors import CORS
from dotenv import load_dotenv
from flask import Flask, request, jsonify, Blueprint
from flask import request, jsonify, Blueprint
bp_support_api = Blueprint('support_api', __name__)
from src.database.connections import get_mongodb_connection
from src.utils.logandcatchexceptions import log_and_catch_exceptions
from src.utils.log import be_logger
load_dotenv()

mongodb_url = os.getenv('MONGODB_URL')
client = MongoClient(mongodb_url)
db = client.get_database()
ip_timestamps = {}
@bp_support_api.route('/api/submit-support', methods=['OPTIONS', 'POST'])
def submit_support_request():
if request.method == 'OPTIONS':
# Handle preflight request
response = jsonify({})
response.headers['Access-Control-Allow-Origin'] = '*'
response.headers['Access-Control-Allow-Methods'] = 'POST'
response.headers['Access-Control-Allow-Headers'] = 'Content-Type'
return response
return handle_preflight_request()

data = request.get_json()

client = get_mongodb_connection()
db = client['Current_Season']
name = data.get('name')
email = data.get('email')
phone = data.get('phone')
message = data.get('message')

# Validate email format
if not email or "@" not in email:
return jsonify({"error": "Invalid email address"}), 400

# Check if the user has already submitted today (based on IP)
user_ip = request.remote_addr
if last_timestamp := ip_timestamps.get(user_ip):
# Calculate time difference in days
days_diff = (datetime.now() - last_timestamp).days

if days_diff < 1:
return jsonify({"error": "You have already submitted today. Please try again tomorrow."}), 400

# Create a dictionary with the submitted data
support_request = {
"name": name,
"email": email,
"phone": phone,
"message": message,
"timestamp": datetime.now()
}

# Insert the support request into MongoDB
try:
db.your_collection_name.insert_one(support_request)
db.SupportEmails.insert_one(support_request)
except Exception as e:
return jsonify({"error": "Failed to insert into MongoDB"}), 500

# Update the timestamp for this IP
return jsonify({"error": "Error inserting support request"}), 500
ip_timestamps[user_ip] = datetime.now()

return jsonify({"message": "Support request submitted successfully"}), 200

def handle_preflight_request():
response = jsonify({})
response.headers['Access-Control-Allow-Origin'] = '*'
response.headers['Access-Control-Allow-Methods'] = 'POST'
response.headers['Access-Control-Allow-Headers'] = 'Content-Type'
return response
2 changes: 1 addition & 1 deletion backend-container/src/nflfetchqueries/fetchlivegames.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
project_root = os.path.abspath(os.path.join(current_dir, '..', '..'))
sys.path.append(project_root)
sys.path.append(os.path.join(project_root, 'src'))

live_games_query_running = False
@log_and_catch_exceptions
def fetch_live_games_data():
global live_games_query_running
Expand Down
18 changes: 9 additions & 9 deletions backend-container/src/utils/auth.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,16 @@
import json
from os import environ as env
from urllib.parse import urlencode
from urllib.parse import quote_plus, urlencode
from authlib.integrations.flask_client import OAuth
from dotenv import load_dotenv
from dotenv import find_dotenv, load_dotenv
from flask import redirect, render_template, session, url_for, Blueprint
load_dotenv()
oauth = OAuth()

if ENV_FILE := find_dotenv():
load_dotenv(ENV_FILE)
auth_blueprint = Blueprint('auth_blueprint', __name__)
auth_blueprint.secret_key = env.get("APP_SECRET_KEY")
def init_oauth(app):
global oauth
oauth = OAuth()
oauth.init_app(app)
oauth.register(
"auth0",
Expand All @@ -20,8 +22,6 @@ def init_oauth(app):
server_metadata_url=f'https://{env.get("AUTH0_DOMAIN")}/.well-known/openid-configuration'
)

auth_blueprint = Blueprint('auth_blueprint', __name__)

@auth_blueprint.route("/login")
def login():
return oauth.auth0.authorize_redirect(
Expand All @@ -32,7 +32,7 @@ def login():
def callback():
token = oauth.auth0.authorize_access_token()
session["user"] = token
return redirect("/auth")
return redirect("/")

@auth_blueprint.route("/logout")
def logout():
Expand All @@ -42,7 +42,7 @@ def logout():
+ "/v2/logout?"
+ urlencode(
{
"returnTo": url_for("auth_blueprint.home", _external=True),
"returnTo": url_for("home", _external=True),
"client_id": env.get("AUTH0_CLIENT_ID"),
},
quote_via=quote_plus,
Expand Down
10 changes: 6 additions & 4 deletions backend-container/src/utils/logandcatchexceptions.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
from functools import wraps
from src.utils.log import be_logger

def log_and_catch_exceptions(func):
@wraps(func)
def func_wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except Exception as e:
be_logger.error(f"Error in {func.__name__}: {e}")
# sourcery skip: raise-specific-error
raise Exception(f"Error in {func.__name__}: {e}")
return func_wrapper
be_logger.error(f"Exception in {func.__name__}: {e}")
raise
return func_wrapper
1 change: 0 additions & 1 deletion frontend-container/src/pages/landing/SupportModal.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import React, { useState } from "react";
import { Modal, Button, Form } from "react-bootstrap";
import axios from "axios";
const apiUrlSubmitSupport = import.meta.env.VITE_SUPPORT_API_URL;
console.log(apiUrlSubmitSupport);
const SupportModal = ({ show, onHide, emailAddress }) => {
const [name, setName] = useState("");
const [email, setEmail] = useState("");
Expand Down
5 changes: 5 additions & 0 deletions manifests/deploy-be.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,11 @@ spec:
value: production
- name: AZURE_STORAGE_ACCOUNT
value: sportfs
- name: APP_SECRET_KEY
valueFrom:
secretKeyRef:
name: auth0-secrets
key: APP_SECRET_KEY
- name: AZURE_STORAGE_KEY
valueFrom:
secretKeyRef:
Expand Down

0 comments on commit 3fd5c32

Please sign in to comment.