Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added connection to mongo db and crud #10

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 51 additions & 0 deletions Database/database.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import os
from typing import Optional

import pymongo


class Database(object):
"""MongoDB CRUD Class """
connection_strong = os.getenv('DB_CONNECTION_STRING') # connect string format mongodb://[
# username:password@]host1[:port1][,...hostN[:portN]][/[defaultauthdb][?options]]
DATABASE = None

@staticmethod
def initialize(db_name: str) -> Optional[Exception]:
"""initialize Database engine """
try:
client = pymongo.MongoClient(Database.connection_strong)
client.admin.command('ismaster')
Database.DATABASE = client[db_name]
return
except Exception as err:
print(str(err))
return err

@staticmethod
def insert(collection: str, data: dict) -> None:
"""insert document to db """
Database.DATABASE[collection].insert_one(data)

@staticmethod
def find(collection: str, query: dict) -> dict:
"""find document in db by id"""
result = Database.DATABASE[collection].find_one(query)
return result if result else {'message': 'data not found'}

@staticmethod
def update(collection: str, document_id: str, data: dict) -> Optional[Exception]:
"""update document in db"""
try:
Database.DATABASE[collection].update_one({'_id': document_id}, {"$set": data})

except Exception as err:
return err

@staticmethod
def delete(collection: str, document_id: str) -> Optional[Exception]:
"""delete document in db by id"""
try:
Database.DATABASE[collection].delete_one({'_id': document_id})
except Exception as err:
return err
3 changes: 3 additions & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,12 @@ bs4==0.0.1
certifi==2021.5.30
charset-normalizer==2.0.6
click==8.0.1
colorama==0.4.4
dnspython==2.1.0
idna==3.2
joblib==1.0.1
nltk==3.6.3
pymongo==3.12.0
regex==2021.8.28
requests==2.26.0
soupsieve==2.2.1
Expand Down