File size: 1,197 Bytes
83fb89d |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
import pymongo
import urllib.parse
import os
def create_db():
"""
Connect to MongoDB Atlas and create collections for the Billing App.
"""
raw_username = os.getenv("DB_USERNAME")
raw_password = os.getenv("DB_PASSWORD")
if not raw_username or not raw_password:
raise Exception("Database credentials are missing. Check your environment variables.")
cluster = "cluster0"
username = urllib.parse.quote_plus(raw_username)
password = urllib.parse.quote_plus(raw_password)
uri = f"mongodb+srv://{username}:{password}@cluster0.yxjok.mongodb.net/?retryWrites=true&w=majority&appName=Cluster0"
client = pymongo.MongoClient(uri)
db = client["billing_app"]
users_coll = db["users"]
sections_coll = db["sections"]
bills_coll = db["bills"]
users_coll.create_index("email", unique=True)
sections_coll.create_index(
[("owner_email", 1), ("section_name", 1)],
unique=True
)
bills_coll.create_index(
[("owner_email", 1), ("section_name", 1), ("participant", 1)]
)
print("Database and collections created (or already exist). Indexes applied.")
if __name__ == "__main__":
create_db()
|