From b8a0fd91794a7bd5990dc0867a303f8ba088ea03 Mon Sep 17 00:00:00 2001 From: tylen Date: Sat, 1 Nov 2025 12:32:01 +0200 Subject: [PATCH] convert from connection to pools in mysql --- .gitignore | 2 + backend/src/db_client.py | 80 +++++++++--------- backend/src/server.py | 4 +- backend/src/user.py | 3 + frontend/src/App.css | 102 ++++++++--------------- frontend/src/App.tsx | 2 + frontend/src/components/InitialSetup.tsx | 5 +- 7 files changed, 84 insertions(+), 114 deletions(-) diff --git a/.gitignore b/.gitignore index ceaea36..49b9e40 100644 --- a/.gitignore +++ b/.gitignore @@ -130,3 +130,5 @@ dist .yarn/install-state.gz .pnp.* + +frontend/src/assets/* diff --git a/backend/src/db_client.py b/backend/src/db_client.py index bf8a8fb..21299dd 100644 --- a/backend/src/db_client.py +++ b/backend/src/db_client.py @@ -1,7 +1,7 @@ from enum import Enum -import sys import mysql.connector import os +from mysql.connector import pooling STARTUP_TABLE_CREATION_QUERIES = { "users": """CREATE TABLE IF NOT EXISTS users ( @@ -21,7 +21,8 @@ class Severity(Enum): ERROR = "ERROR" class DBClient: - def __init__(self): + def __init__(self, app): + self.app = app self.db_server = os.environ.get('DB_SERVER') self.db_port = os.environ.get('DB_PORT') self.user = 'root' @@ -29,57 +30,54 @@ class DBClient: self.database = os.environ.get('DB_NAME') self.validate_env_variables() # Check for required environment variables - self.connection = self.open() - self.cursor = self.connection.cursor() + self.pool = self.create_pool() # Create a connection pool self.initialize_database() def validate_env_variables(self): if not self.db_server or not self.db_port or not self.password or not self.database: - self.error("Missing one or more environment variables.") - - def open(self): - return mysql.connector.connect( + self.app.logger.error("Missing one or more environment variables.") + + def create_pool(self): + return pooling.MySQLConnectionPool( + pool_name="mypool", + pool_size=5, # Adjust size as needed host=self.db_server, port=self.db_port, user=self.user, password=self.password, - database=self.database + database=self.database, + connection_timeout=10 # Timeout in seconds ) - def close(self): - self.cursor.close() - self.connection.close() - def initialize_database(self): self.query(STARTUP_TABLE_CREATION_QUERIES['users']) self.query(STARTUP_TABLE_CREATION_QUERIES['sessions']) - def query(self, query_str, params=None): - try: - self.info(f'Executing query: {query_str}') - self.cursor.execute(query_str, params) - - if 'SELECT' in query_str: - return self.cursor.fetchall() # Return results for SELECT queries - else: - self.commit() # Commit if it's a non-SELECT query - except Exception as e: - self.error(f"Query failed: {str(e)}") - - def commit(self): - self.info('Committing actions to DB') - self.connection.commit() - - def info(self, message): - self.message(severity=Severity.INFO, message=message) - - def warning(self, message): - self.message(severity=Severity.WARNING, message=message) - - def error(self, message): - self.message(severity=Severity.ERROR, message=message) - - def message(self, severity, message): - print(f'DBClient [{severity.value}]: {message}') - + def query(self, query_str, params=None): + max_retries = 3 + for attempt in range(max_retries): + try: + self.app.logger.info(f'Executing query: {query_str}') + # Get a connection from the pool + connection = self.pool.get_connection() + with connection.cursor() as cursor: + cursor.execute(query_str, params) + if 'SELECT' in query_str: + results = cursor.fetchall() + self.app.logger.info(f'Query results: {results}') + return results + else: + connection.commit() + self.app.logger.info('Query executed successfully, changes committed.') + break + except mysql.connector.Error as e: + if e.errno in (2013, 2006): # Lost connection or connection no longer available + self.app.logger.warning(f"Lost connection to MySQL, retrying... {attempt + 1}/{max_retries}") + continue # Retry the query + else: + self.app.logger.error(f"Query failed: {str(e)}") + return None # Handle the error accordingly + finally: + if connection.is_connected(): + connection.close() # Close the connection to return it to the pool diff --git a/backend/src/server.py b/backend/src/server.py index 2384d22..0b57729 100644 --- a/backend/src/server.py +++ b/backend/src/server.py @@ -10,16 +10,18 @@ from flask_cors import CORS from dotenv import load_dotenv from db_client import DBClient from user import registerUserEndpoints +import logging load_dotenv() app = Flask(__name__) app.config['JSON_AS_ASCII'] = False # Ensures non-ASCII characters are preserved +logging.basicConfig(level=logging.INFO) allowed_origins = [ "https://nyipyatki.davydovcloud.com", "https://nyipyatki-dev.davydovcloud.com", ] CORS(app, resources={r"*": {"origins": allowed_origins}}) # Only allow example.com -database = DBClient() +database = DBClient(app) registerUserEndpoints(app=app, database=database) if __name__ == "__main__": diff --git a/backend/src/user.py b/backend/src/user.py index 7f34c71..d123a18 100644 --- a/backend/src/user.py +++ b/backend/src/user.py @@ -14,8 +14,10 @@ def registerUserEndpoints(app, database): def user_is_set(): user_name = request.args.get('userName') try: + app.logger.info(f'Searching for user {user_name}') query = "SELECT * FROM users WHERE Name=%s" result = database.query(query, params=(user_name,)) + app.logger.info(f'Got: {result}') return jsonify(bool(result)), 200 except mysql.connector.Error as err: # Log the error or handle it as necessary @@ -79,6 +81,7 @@ def registerUserEndpoints(app, database): query = "SELECT * FROM sessions WHERE Token=%s AND Name=%s" try: result = database.query(query, params=(token, user_name)) + app.logger.info(f'Got result: {result}') return jsonify(tokenValid=bool(result)), 200 except Exception as e: return jsonify(success=False, message=str(e)), 500 diff --git a/frontend/src/App.css b/frontend/src/App.css index 1183841..326ab95 100644 --- a/frontend/src/App.css +++ b/frontend/src/App.css @@ -1,15 +1,16 @@ #root { width: 100%; max-width: 1280px; - text-align: center; + text-align: center; /* Centered text alignment */ } /* Overall Body Style */ body { - background-color: #b8b6b6; /* Light background for contrast */ + background-color: #ffffff; /* Light background for contrast */ color: #4b2e2e; /* Darker red brown for readability */ font-family: 'Arial', sans-serif; margin: 0; + text-align: center; /* Centered text alignment */ padding: 20px; } @@ -17,7 +18,6 @@ body { header { background-color: #a41e34; /* Christmas red */ color: white; - text-align: center; padding: 20px 0; border-bottom: 5px solid #b7c9b5; /* Light green border */ } @@ -26,19 +26,6 @@ header h1 { font-size: 2.5em; } -/* Navigation Menu */ -nav a { - text-decoration: none; - color: white; - padding: 15px 25px; - border-radius: 5px; - transition: background-color 0.3s; -} - -nav a:hover { - background-color: #c28f8f; /* Softer red when hovering */ -} - /* Section Style */ section { background-color: #e4f7e0; /* Light green background */ @@ -56,43 +43,38 @@ button { border-radius: 5px; cursor: pointer; font-size: 1.1em; + display: inline-block; /* Centers button in the container */ } button:hover { background-color: #9b6bb5; /* Darker purple on hover */ } +button:disabled { + background-color: #d3d3d3; /* Light gray for disabled button */ + color: #a9a9a9; /* Darker gray for text */ + cursor: not-allowed; /* Show not-allowed cursor */ +} + /* Footer Style */ footer { - text-align: center; + text-align: center; /* Centered */ padding: 20px; background-color: #a41e34; /* Same red as header */ color: white; position: relative; } -/* Christmas Decorations */ -.christmas-tree { - background-image: url('path/to/christmas-tree.png'); /* Add a Christmas tree image */ - width: 50px; - height: 100px; - display: inline-block; - background-size: cover; -} - +/* Snowflakes Background */ .snowflakes { position: absolute; - z-index: 1; top: 0; left: 0; width: 100%; height: 100%; - background-image: url('path/to/snowflake-pattern.png'); /* Snowflakes pattern */ - opacity: 0.3; /* Make it subtle */ - pointer-events: none; /* Allow clicks to go through */ + background-image: url('./assets/snowflakes.png'); /* Snowflakes pattern */ } - /* General table styles */ table { width: 100%; @@ -100,78 +82,60 @@ table { margin: 20px 0; font-size: 1em; font-family: 'Arial', sans-serif; + text-align: center; /* Centered table text */ } /* Table header styles */ th { - background-color: #a41e34; - /* Christmas red */ + background-color: #060698; /* Christmas red */ color: white; - text-align: left; padding: 10px 15px; - border-bottom: 3px solid #b7c9b5; - /* Light green border for header */ + border-bottom: 3px solid #b7c9b5; /* Light green border for header */ } /* Table cell styles */ td { border: 1px solid #ddd; - padding: 10px 15px; - /* Added padding for better spacing */ - background-color: #e4f7e0; - /* Light green background for cells */ + padding: 10px 15px; /* Added padding for better spacing */ + background-color: #e4f7e0; /* Light green background for cells */ } /* Zebra striping for table rows */ tr:nth-child(even) { - background-color: #f9f9f9; - /* Light gray for even rows */ + background-color: #f9f9f9; /* Light gray for even rows */ } /* Hover effect for rows */ tr:hover { - background-color: #c28f8f; - /* Softer red when hovering */ + background-color: #c28f8f; /* Softer red when hovering */ } /* Additional table styling for Christmas theme */ table { - box-shadow: 0 4px 10px rgba(0, 0, 0, 0.2); - /* Shadow for depth */ - border-radius: 8px; - /* Rounded corners */ - overflow: hidden; - /* Ensures border radius works */ + box-shadow: 0 4px 10px rgba(0, 0, 0, 0.2); /* Shadow for depth */ + border-radius: 8px; /* Rounded corners */ + overflow: hidden; /* Ensures border radius works */ } /* Add some festive decorations */ th::after { - content: '🎄'; - /* Small Christmas tree icon in the header */ + content: '🎄'; /* Small Christmas tree icon in the header */ margin-left: 10px; - font-size: 1.2em; - /* Slightly larger */ + font-size: 1.2em; /* Slightly larger */ } td { - position: relative; - /* For potential decorations */ + position: relative; /* For potential decorations */ } td::before { - content: ''; - /* Placeholder for decoration */ + content: ''; /* Placeholder for decoration */ position: absolute; - background-image: url('path/to/snowflake-icon.png'); - /* Snowflake icon */ - width: 16px; - /* Adjust as necessary */ + background-image: url('path/to/snowflake-icon.png'); /* Snowflake icon */ + width: 16px; /* Adjust as necessary */ height: 16px; - opacity: 0.1; - /* Very subtle */ - top: 5px; - /* Position it nicely */ + opacity: 0.1; /* Very subtle */ + top: 5px; /* Position it nicely */ left: 5px; - pointer-events: none; - /* Ignore mouse events */ -} \ No newline at end of file + pointer-events: none; /* Ignore mouse events */ +} diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index fee3b1d..8d5488a 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -7,11 +7,13 @@ import Program from './components/Program' function App() { return ( <> +

+
) } diff --git a/frontend/src/components/InitialSetup.tsx b/frontend/src/components/InitialSetup.tsx index dfc2e7b..c7a74d3 100644 --- a/frontend/src/components/InitialSetup.tsx +++ b/frontend/src/components/InitialSetup.tsx @@ -32,9 +32,8 @@ const InitialSetup = () => { const isTokenValid = await validToken(token, selectedName); setIsSubmitted(isTokenValid); }; - if (selectedName !== undefined) checkUserPassword(selectedName) - if (token && selectedName) validateToken(); - }, [selectedName]); + if (token !== undefined && selectedName !== undefined) validateToken(); + }, []); const handlePasswordCreate = async () => {