diff --git a/Database/database.py b/Database/database.py new file mode 100644 index 0000000..99a9cf8 --- /dev/null +++ b/Database/database.py @@ -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 diff --git a/requirements.txt b/requirements.txt index c5515b5..02b7e01 100644 --- a/requirements.txt +++ b/requirements.txt @@ -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