-
Notifications
You must be signed in to change notification settings - Fork 0
/
db.py
30 lines (27 loc) · 874 Bytes
/
db.py
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
from pymongo import MongoClient
import logging
import os
def connect_to_mongodb(uri):
try:
client = MongoClient(uri)
client.admin.command('ping')
logging.info("Successfully connected to MongoDB!")
return client
except Exception as e:
logging.error(f"Failed to connect to MongoDB: {e}")
return None
def get_database(uri, dbname):
client = connect_to_mongodb(uri)
if client is not None:
return client[dbname]
else:
logging.error("Client is None, cannot get database.")
return None
def insert_article(collection, article):
try:
insert_result = collection.insert_one(article)
print(f"Inserted article with ID: {insert_result.inserted_id}")
return insert_result
except Exception as e:
print(f"Error inserting article: {e}")
return None