Skip to content

Commit 83ca86d

Browse files
committed
db-connection
1 parent acf77e2 commit 83ca86d

5 files changed

Lines changed: 183 additions & 70 deletions

File tree

.env.example

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,12 @@
11
# MongoDB Configuration
2-
MONGODB_URI=mongodb://localhost:27017/traders_arena
2+
MONGODB_URI="mongodb+srv://username:password@cluster.mongodb.net/traders_arena?retryWrites=true&w=majority&appName=TradersArena"
33

44
# Authentication
5-
USERS=admin,manager
5+
USERS=admin
66
PASSWORD=your_secure_password
77

8-
# Optional Server Configuration
9-
SERVER_NAME=localhost:5000
8+
# Optional: Secret key for session encryption (will use default if not provided)
9+
SECRET_KEY=your_secret_key_here
10+
11+
# Optional: Server Configuration for production
12+
# SERVER_NAME=yourdomain.com

app.py

Lines changed: 104 additions & 66 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
from datetime import datetime, timedelta, timezone
77
import time
88
import base64
9+
import traceback
910

1011
from flask import Flask, render_template, request, redirect, url_for, jsonify, session, flash
1112
from flask_pymongo import PyMongo
@@ -16,13 +17,35 @@
1617
from pymongo.errors import PyMongoError
1718

1819
app = Flask(__name__)
19-
app.config["MONGODB_URI"] = os.getenv("MONGODB_URI")
20-
app.config['SESSION_TYPE'] = 'mongodb'
20+
21+
# Load and validate MongoDB URI
22+
mongodb_uri = os.getenv("MONGODB_URI")
23+
if not mongodb_uri:
24+
print("ERROR: MONGODB_URI not found in environment variables")
25+
print("Available environment variables:")
26+
for key in sorted(os.environ.keys()):
27+
if 'MONGO' in key.upper() or 'DB' in key.upper():
28+
print(f" {key}: {os.environ[key][:30]}...")
29+
raise ValueError("MONGODB_URI is required")
30+
31+
print(f"MongoDB URI loaded: {mongodb_uri[:50]}...")
32+
app.config["MONGO_URI"] = mongodb_uri
33+
app.config['SESSION_TYPE'] = 'filesystem' # Changed from 'mongodb' to 'filesystem' to avoid session store issues
2134
app.secret_key = os.getenv("SECRET_KEY", "traders_arena_secret_key")
22-
mongo = PyMongo(app)
35+
36+
# Initialize MongoDB
37+
try:
38+
mongo = PyMongo(app)
39+
print("PyMongo initialized successfully")
40+
except Exception as e:
41+
print(f"Error initializing PyMongo: {e}")
42+
raise
43+
2344
server_name = os.getenv("SERVER_NAME")
2445
if server_name:
2546
app.config["SERVER_NAME"] = server_name
47+
48+
# Initialize Flask-Session after MongoDB
2649
Session(app)
2750

2851
# MongoDB Collection Schemas and Validators
@@ -74,65 +97,86 @@ def get_team_validator():
7497

7598
# Initialize MongoDB collections with schemas and indexes
7699
def init_mongodb():
100+
with app.app_context():
101+
try:
102+
# Test the connection first
103+
if mongo.db is None:
104+
raise Exception("MongoDB database connection is None - check your MONGO_URI")
105+
106+
# Test basic connectivity
107+
result = mongo.db.command('ping')
108+
print(f"MongoDB ping successful: {result}")
109+
print(f"Connected to database: {mongo.db.name}")
110+
111+
# Create collections with validation
112+
db = mongo.db
113+
114+
# Competitions
115+
if "competitions" not in db.list_collection_names():
116+
db.create_collection("competitions")
117+
db.command("collMod", "competitions", validator=get_competition_validator())
118+
db.competitions.create_index([("competitionName", ASCENDING)], unique=True)
119+
db.competitions.create_index([("timeOfCreation", DESCENDING)])
120+
121+
# Stocks
122+
if "stocks" not in db.list_collection_names():
123+
db.create_collection("stocks")
124+
db.command("collMod", "stocks", validator=get_stock_validator())
125+
db.stocks.create_index([("competition_id", ASCENDING), ("name", ASCENDING)], unique=True)
126+
127+
# Teams
128+
if "teams" not in db.list_collection_names():
129+
db.create_collection("teams")
130+
db.command("collMod", "teams", validator=get_team_validator())
131+
db.teams.create_index([("participant_id", ASCENDING)], unique=True)
132+
db.teams.create_index([("competition_id", ASCENDING), ("teamName", ASCENDING)], unique=True)
133+
134+
# Rounds
135+
if "rounds" not in db.list_collection_names():
136+
db.create_collection("rounds")
137+
db.rounds.create_index([
138+
("competition_id", ASCENDING),
139+
("stock_id", ASCENDING),
140+
("round_number", ASCENDING)
141+
])
142+
143+
# Transactions
144+
if "transactions" not in db.list_collection_names():
145+
db.create_collection("transactions")
146+
db.transactions.create_index([("competition_id", ASCENDING), ("timeOfTransaction", DESCENDING)])
147+
db.transactions.create_index([("buyer_team", ASCENDING)])
148+
db.transactions.create_index([("seller_team", ASCENDING)])
149+
150+
# Stock Purchases
151+
if "stock_purchases" not in db.list_collection_names():
152+
db.create_collection("stock_purchases")
153+
db.stock_purchases.create_index([("competition_id", ASCENDING)])
154+
db.stock_purchases.create_index([("team", ASCENDING)])
155+
db.stock_purchases.create_index([("timeIssued", DESCENDING)])
156+
157+
# Stock News
158+
if "stock_news" not in db.list_collection_names():
159+
db.create_collection("stock_news")
160+
db.stock_news.create_index([("competition_id", ASCENDING), ("roundNumber", ASCENDING)])
161+
162+
print("MongoDB initialized successfully with schemas and indexes")
163+
except PyMongoError as e:
164+
print(f"Error initializing MongoDB: {e}")
165+
raise
166+
167+
# Initialize MongoDB on startup - wrap in a function to handle errors gracefully
168+
def initialize_app():
77169
try:
78-
# Create collections with validation
79-
db = mongo.db
80-
81-
# Competitions
82-
if "competitions" not in db.list_collection_names():
83-
db.create_collection("competitions")
84-
db.command("collMod", "competitions", validator=get_competition_validator())
85-
db.competitions.create_index([("competitionName", ASCENDING)], unique=True)
86-
db.competitions.create_index([("timeOfCreation", DESCENDING)])
87-
88-
# Stocks
89-
if "stocks" not in db.list_collection_names():
90-
db.create_collection("stocks")
91-
db.command("collMod", "stocks", validator=get_stock_validator())
92-
db.stocks.create_index([("competition_id", ASCENDING), ("name", ASCENDING)], unique=True)
93-
94-
# Teams
95-
if "teams" not in db.list_collection_names():
96-
db.create_collection("teams")
97-
db.command("collMod", "teams", validator=get_team_validator())
98-
db.teams.create_index([("participant_id", ASCENDING)], unique=True)
99-
db.teams.create_index([("competition_id", ASCENDING), ("teamName", ASCENDING)], unique=True)
100-
101-
# Rounds
102-
if "rounds" not in db.list_collection_names():
103-
db.create_collection("rounds")
104-
db.rounds.create_index([
105-
("competition_id", ASCENDING),
106-
("stock_id", ASCENDING),
107-
("round_number", ASCENDING)
108-
])
109-
110-
# Transactions
111-
if "transactions" not in db.list_collection_names():
112-
db.create_collection("transactions")
113-
db.transactions.create_index([("competition_id", ASCENDING), ("timeOfTransaction", DESCENDING)])
114-
db.transactions.create_index([("buyer_team", ASCENDING)])
115-
db.transactions.create_index([("seller_team", ASCENDING)])
116-
117-
# Stock Purchases
118-
if "stock_purchases" not in db.list_collection_names():
119-
db.create_collection("stock_purchases")
120-
db.stock_purchases.create_index([("competition_id", ASCENDING)])
121-
db.stock_purchases.create_index([("team", ASCENDING)])
122-
db.stock_purchases.create_index([("timeIssued", DESCENDING)])
123-
124-
# Stock News
125-
if "stock_news" not in db.list_collection_names():
126-
db.create_collection("stock_news")
127-
db.stock_news.create_index([("competition_id", ASCENDING), ("roundNumber", ASCENDING)])
128-
129-
print("MongoDB initialized successfully with schemas and indexes")
130-
except PyMongoError as e:
131-
print(f"Error initializing MongoDB: {e}")
132-
raise
170+
init_mongodb()
171+
print("Application initialized successfully")
172+
except Exception as e:
173+
print(f"Warning: Could not initialize MongoDB collections: {e}")
174+
print("Application will continue to run, but database features may not work properly")
175+
print("Please check your MONGODB_URI and internet connectivity")
133176

134-
# Initialize MongoDB on startup
135-
init_mongodb()
177+
# Call initialization only when not in debug/reloader mode
178+
if not os.environ.get('WERKZEUG_RUN_MAIN'):
179+
initialize_app()
136180

137181
def generate_team_id():
138182
"""Generate a random 6-character alphanumeric ID"""
@@ -1055,7 +1099,6 @@ def results(competition_id):
10551099
except Exception as e:
10561100
print(f"Error in results: {e}")
10571101
print(f"Error type: {type(e)}")
1058-
import traceback
10591102
traceback.print_exc()
10601103
flash(f"An error occurred: {str(e)}", "error")
10611104
return render_template(
@@ -1223,7 +1266,6 @@ def transactions(competition_id):
12231266
except Exception as e:
12241267
print(f"Error in trading page: {e}")
12251268
print(f"Error type: {type(e)}")
1226-
import traceback
12271269
traceback.print_exc()
12281270
flash(f"An error occurred: {str(e)}", "error")
12291271
# Render the template with error instead of redirecting
@@ -1357,7 +1399,6 @@ def stocksIssue(competition_id):
13571399
except Exception as e:
13581400
print(f"Error recording stock purchase: {e}")
13591401
print(f"Error type: {type(e)}")
1360-
import traceback
13611402
traceback.print_exc()
13621403

13631404
# Update portfolio trend
@@ -1398,7 +1439,6 @@ def stocksIssue(competition_id):
13981439
except Exception as e:
13991440
print(f"Error in initial buying: {e}")
14001441
print(f"Error type: {type(e)}")
1401-
import traceback
14021442
traceback.print_exc()
14031443
flash(f"An error occurred: {str(e)}", "error")
14041444
return render_template(
@@ -1527,7 +1567,6 @@ def complete_competition():
15271567
except Exception as e:
15281568
print(f"Error completing competition: {e}")
15291569
print(f"Error type: {type(e)}")
1530-
import traceback
15311570
traceback.print_exc()
15321571
flash(f"Failed to complete competition: {str(e)}", "error")
15331572
return redirect("/dashboard")
@@ -1676,7 +1715,6 @@ def next_round():
16761715
except Exception as e:
16771716
print(f"Error advancing round: {e}")
16781717
print(f"Error type: {type(e)}")
1679-
import traceback
16801718
traceback.print_exc()
16811719
flash(f"Failed to advance to next round: {str(e)}", "error")
16821720
return redirect("/dashboard")
9 Bytes
Binary file not shown.

start.sh

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
#!/bin/bash
2+
# Render startup script
3+
4+
# Start the application with gunicorn
5+
exec gunicorn --bind 0.0.0.0:$PORT app:app

test_mongo.py

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
#!/usr/bin/env python3
2+
3+
import os
4+
import sys
5+
from dotenv import load_dotenv
6+
7+
print("Loading environment...")
8+
# Load environment variables
9+
load_dotenv()
10+
11+
print("Importing pymongo...")
12+
try:
13+
from pymongo import MongoClient
14+
print("✅ PyMongo imported successfully")
15+
except ImportError as e:
16+
print(f"❌ Failed to import pymongo: {e}")
17+
sys.exit(1)
18+
19+
# Test MongoDB connection
20+
def test_mongo_connection():
21+
mongodb_uri = os.getenv("MONGODB_URI")
22+
if not mongodb_uri:
23+
print("ERROR: MONGODB_URI not found")
24+
return False
25+
26+
print(f"Testing connection to: {mongodb_uri[:50]}...")
27+
28+
try:
29+
# Test with direct pymongo client with timeout
30+
print("Creating MongoClient...")
31+
client = MongoClient(mongodb_uri, serverSelectionTimeoutMS=5000)
32+
33+
print("Getting default database...")
34+
# Test connection
35+
db = client.get_default_database()
36+
print(f"Default database name: {db.name}")
37+
38+
print("Testing ping...")
39+
# Test ping
40+
result = db.command("ping")
41+
print(f"Ping result: {result}")
42+
43+
print("Listing collections...")
44+
# List collections
45+
collections = db.list_collection_names()
46+
print(f"Existing collections: {collections}")
47+
48+
print("✅ MongoDB connection successful!")
49+
return True
50+
51+
except Exception as e:
52+
print(f"❌ MongoDB connection failed: {e}")
53+
print(f"Error type: {type(e)}")
54+
import traceback
55+
traceback.print_exc()
56+
return False
57+
finally:
58+
try:
59+
print("Closing client...")
60+
client.close()
61+
except:
62+
pass
63+
64+
if __name__ == "__main__":
65+
print("Starting MongoDB connection test...")
66+
test_mongo_connection()
67+
print("Test completed.")

0 commit comments

Comments
 (0)