Spaces:
Sleeping
Sleeping
File size: 15,781 Bytes
60f01af |
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 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 |
'''
Copyright 2024 Infosys Ltd.
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
'''
import os
import pymongo
# from dotenv import load_dotenv
from config.logger import CustomLogger,request_id_var
# import sys
# load_dotenv()
import json
import requests
import hvac
import urllib.parse
# import psycopg2
from azure.identity import ClientSecretCredential
from azure.keyvault.secrets import SecretClient
import traceback
from sqlalchemy import create_engine
from sqlalchemy import text
import json
import time
log = CustomLogger()
class AttributeDict(dict):
__getattr__ = dict.__getitem__
__setattr__ = dict.__setitem__
__delattr__ = dict.__delitem__
request_id_var.set("Startup")
global conn
conn=None
try:
vault = os.getenv("ISVAULT")
if vault=="True":
vaultname = os.getenv("VAULTNAME")
if vaultname=="HASHICORP":
payload = {'role_id': os.getenv("APP_VAULT_ROLE_ID"),'secret_id': os.getenv("APP_VAULT_SECRET_ID")}
r = requests.post(os.getenv("APP_VAULT_URL")+"/v1/auth/approle/login",data=json.dumps(payload))
r.raise_for_status()
data = r.json()
token=data["auth"]["client_token"]
print("Vault token generator")
client = hvac.Client(url=os.getenv("APP_VAULT_URL"),token=token)
# secret = client.read(os.getenv("VAULTENGINE"))
secret = client.secrets.kv.v2.read_secret_version(
path=os.getenv("APP_VAULT_PATH"),
mount_point=os.getenv("APP_VAULT_BACKEND"),
)["data"]["data"]
dbname = os.getenv("APP_MONGO_DBNAME")
encoded_password = urllib.parse.quote(secret[os.getenv("APP_VAULT_KEY_MONGOPASS")], safe='')
if os.getenv("DBTYPE")=="mongo":
myclient=pymongo.MongoClient("mongodb://"+secret[os.getenv("APP_VAULT_KEY_MONGOUSER")]+":"+encoded_password+"@"+os.getenv("APP_MONGO_HOST")+"/"+"?authMechanism=SCRAM-SHA-256&authSource="+dbname)
print("myclient is here -> ",myclient)
elif os.getenv("DBTYPE")=="psql":
#-------- Migrating to SQLAlchemy from Psycopg2 due to IP Check issue -----#
HOST = os.getenv("APP_MONGO_HOST")
engine = create_engine(f'postgresql://{secret[os.getenv("APP_VAULT_KEY_MONGOUSER")]}:{secret[os.getenv("APP_VAULT_KEY_MONGOPASS")]}@{HOST.split(":")[0]}:{HOST.split(":")[1]}/{dbname}')
create_table_query = '''
CREATE TABLE IF NOT EXISTS ModerationResult (
id VARCHAR(50) PRIMARY KEY,
payload JSONB
)
'''
create_log_table_query = '''
CREATE TABLE IF NOT EXISTS log_db (
id VARCHAR(50) PRIMARY KEY,
error JSONB
)
'''
with engine.connect() as conn:
conn.execute(text(create_table_query))
conn.execute(text(create_log_table_query))
conn.commit()
else:
myclient=pymongo.MongoClient("mongodb://"+secret[os.getenv("APP_VAULT_KEY_MONGOUSER")]+":"+encoded_password+"@"+os.getenv("APP_MONGO_HOST")+"/"+"?ssl=true&replicaSet=globaldb&retrywrites=false&maxIdleTimeMS=120000&appName="+"@"+secret[os.getenv("APP_VAULT_KEY_MONGOUSER")])
elif vaultname=="AZURE":
print("AZURE VaultIntegration Starts")
credential = ClientSecretCredential(
tenant_id = os.getenv("AZURE_VAULT_TENANT_ID"),
client_id = os.getenv("AZURE_VAULT_CLIENT_ID"),
client_secret = os.getenv("VAULT_SECRET")
)
sc = SecretClient(vault_url = os.getenv("KEYVAULTURL"), credential=credential)
try:
DB_USERNAME = sc.get_secret(os.getenv("APP_VAULT_KEY_MONGOUSER")).value
DB_PWD = sc.get_secret(os.getenv("APP_VAULT_KEY_MONGOPASS")).value
print("Retrived username and password")
except Exception as e:
print('########### Exception occured #######',e)
log.error("error in Azure vault")
traceback.print_exc()
dbname = os.getenv("APP_MONGO_DBNAME")
encoded_password = urllib.parse.quote(DB_PWD, safe='')
if os.getenv("DBTYPE")=="mongo":
myclient=pymongo.MongoClient("mongodb://"+DB_USERNAME+":"+encoded_password+"@"+os.getenv("APP_MONGO_HOST")+"/"+"?authMechanism=SCRAM-SHA-256&authSource="+dbname)
elif os.getenv("DBTYPE")=="psql":
#-------- Migrating to SQLAlchemy from Psycopg2 due to IP Check issue -----#
HOST = os.getenv("APP_MONGO_HOST")
engine = create_engine(f'postgresql://{sc.get_secret(os.getenv("APP_VAULT_KEY_MONGOUSER")).value}:{sc.get_secret(os.getenv("APP_VAULT_KEY_MONGOPASS")).value}@{HOST.split(":")[0]}:{HOST.split(":")[1]}/{dbname}')
create_table_query = '''
CREATE TABLE IF NOT EXISTS ModerationResult (
id VARCHAR(50) PRIMARY KEY,
payload JSONB
)
'''
create_log_table_query = '''
CREATE TABLE IF NOT EXISTS log_db (
id VARCHAR(50) PRIMARY KEY,
error JSONB
)
'''
with engine.connect() as conn:
conn.execute(text(create_table_query))
conn.execute(text(create_log_table_query))
conn.commit()
else:
myclient=pymongo.MongoClient("mongodb://"+DB_USERNAME+":"+encoded_password+"@"+os.getenv("APP_MONGO_HOST")+"/"+"?ssl=true&replicaSet=globaldb&retrywrites=false&maxIdleTimeMS=120000&appName="+"@"+DB_USERNAME)
else:
dbname = os.getenv("APP_MONGO_DBNAME")
if os.getenv("DBTYPE")=="mongo":
myclient = pymongo.MongoClient(os.getenv("MONGO_PATH"))
elif os.getenv("DBTYPE")=="psql":
#-------- Migrating to SQLAlchemy from Psycopg2 due to IP Check issue -----#
HOST = os.getenv("APP_MONGO_HOST")
engine = create_engine(f'postgresql://{os.getenv("DB_USERNAME")}:{os.getenv("DB_PWD")}@{HOST.split(":")[0]}:{HOST.split(":")[1]}/{dbname}')
create_table_query = '''
CREATE TABLE IF NOT EXISTS ModerationResult (
id VARCHAR(50) PRIMARY KEY,
payload JSONB
)
'''
create_log_table_query = '''
CREATE TABLE IF NOT EXISTS log_db (
id VARCHAR(50) PRIMARY KEY,
error JSONB
)
'''
with engine.connect() as conn:
conn.execute(text(create_table_query))
conn.execute(text(create_log_table_query))
conn.commit()
elif os.getenv("DBTYPE")=="cosmos":
DB_USERNAME = os.getenv("DB_USERNAME")
DB_PWD = os.getenv("DB_PWD")
encoded_password = urllib.parse.quote(DB_PWD, safe='')
myclient=pymongo.MongoClient("mongodb://"+DB_USERNAME+":"+encoded_password+"@"+os.getenv("APP_MONGO_HOST")+"/"+"?ssl=true&replicaSet=globaldb&retrywrites=false&maxIdleTimeMS=120000&appName="+"@"+DB_USERNAME)
print(myclient)
except Exception as e:
print("friest error is here ->" ,e)
log.error("error in vault")
log.error(str(traceback.extract_tb(e.__traceback__)[0].lineno),e)
class DB:
def connect():
try:
# myclient = pymongo.MongoClient(os.getenv("MONGO_PATH"))
# mydb = myclient[os.getenv("APP_MONGO_DBNAME")]
mydb = myclient[dbname]
return mydb
except Exception as e:
print("error here -> ",e)
log.error("error in DB connection")
log.error(str(traceback.extract_tb(e.__traceback__)[0].lineno),e)
if conn == None:
mydb=DB.connect()
class ProfaneWords:
def findOne(id):
try:
mycol = mydb["ProfaneWords"]
values=ProfaneWords.mycol.find({"_id":id},{})[0]
# print(values)
values=AttributeDict(values)
return values
except Exception as e:
log.error("Error occured in ProfaneWords")
log.error(f"Exception: {e}")
class feedbackdb:
# feedback_collection = mydb["feedback"]
def create(value):
try:
feedback_collection = mydb["feedback"]
PtrnRecogCreatedData = feedbackdb.feedback_collection.insert_one(value)
print("PtrnRecogCreatedData.acknowledged",PtrnRecogCreatedData.acknowledged)
return PtrnRecogCreatedData.acknowledged
except Exception as e:
log.error("Error occured in feedbackdb")
log.error(f"Exception: {e}")
class Results:
# mycol = mydb["moderationtelemetrydata"]
if conn == None:
logdb=mydb["Logdb"]
mycol = mydb["Results"]
mycol2 = mydb["Results"]
# mycol2 = mydb["Resultswithfeedback"]
def findOne(id):
try:
print("came inside findOne")
print(Results.mycol)
values=Results.mycol.find({"_id":id},{})[0]
print("values -------> ",values)
values=AttributeDict(values)
return values
except Exception as e:
log.error("Error occured in Results findOne")
log.error(f"Exception: {e}")
def findall(query):
try:
value_list=[]
values=Results.mycol.find(query,{})
for v in values:
v=AttributeDict(v)
value_list.append(v)
return value_list
except Exception as e:
log.error("Error occured in Results findall")
log.error(f"Exception: {e}")
def create(value,id,portfolio, accountname,user=None,lotnumber=None):
request_id_var.set(id)
try:
if type(value) is not dict:
value=json.loads(value.json())
id=value["uniqueid"]
if user:
mydoc={"_id":id , "created":value["created"],"user":user,"lotnumber":lotnumber,"portfolio":portfolio,"accountname":accountname,
"Moderations":value["moderationResults"]}
else:
mydoc={"_id":id , "created":value["created"],"portfolio":portfolio,"accountname":accountname, "lotnumber":lotnumber,
"Moderations":value["moderationResults"]}
# if conn != None: #Postgresql Connection
if os.getenv("DBTYPE")=="psql": #Postgresql Connection
#-------- Migrating to SQLAlchemy from Psycopg2 due to IP Check issue -----#
# json_col =json.dumps(mydoc)
# query = "INSERT INTO ModerationResult(id, payload) VALUES (%s, %s)"
# data = (id, json_col)
with engine.connect() as conn:
conn.execute(
text("INSERT INTO ModerationResult(id, payload) VALUES (:id, :payload)"),
[{"id": id, "payload": json.dumps(mydoc)}],
)
conn.commit()
# cursor.execute(query, data)
# conn.commit()
return "PtrnRecogCreatedData"
else:
PtrnRecogCreatedData = Results.mycol.insert_one(mydoc)
print("PtrnRecogCreatedData.acknowledged",PtrnRecogCreatedData.acknowledged)
return PtrnRecogCreatedData.acknowledged
except Exception as e:
log.error("Error occured in Results create")
log.error(f"Exception: {str(traceback.extract_tb(e.__traceback__)[0].lineno),e}")
def createlog(value):
try:
value["created"]=time.time()
# if conn != None: #Postgresql Connection
if os.getenv("DBTYPE")=="psql": #Postgresql Connection
#-------- Migrating to SQLAlchemy from Psycopg2 due to IP Check issue -----#
# json_col =json.dumps(value)
# query = "INSERT INTO log_db(id, error) VALUES (%s, %s)"
# data = (value["_id"], json_col)
with engine.connect() as conn:
conn.execute(
text("INSERT INTO log_db(id, error) VALUES (:id, :error)"),
[{"id": value["_id"], "error": json.dumps(value)}],
)
conn.commit()
# cursor.execute(query, data)
# conn.commit()
return "PtrnRecogCreatedData"
else:
PtrnRecogCreatedData = Results.logdb.insert_one(value)
print("Log added",PtrnRecogCreatedData.acknowledged)
return PtrnRecogCreatedData.acknowledged
except Exception as e:
log.error("Error occured in Log saving")
log.error(f"Exception: {str(traceback.extract_tb(e.__traceback__)[0].lineno),e}")
def createwithfeedback(value):
try:
# print(id)
PtrnRecogCreatedData = Results.mycol2.insert_one(value)
print("PtrnRecogCreatedData.acknowledged",PtrnRecogCreatedData.acknowledged)
return PtrnRecogCreatedData.acknowledged
except Exception as e:
log.error("Error occured in createwithfeedback")
log.error(f"Exception: {e}")
def update(query,value:dict):
try:
newvalues = { "$set": value }
PtrnRecogUpdatedData=Results.mycol.update_one(query,newvalues)
log.debug(str(newvalues))
return PtrnRecogUpdatedData.acknowledged
except Exception as e:
log.error("Error occured in Results update")
log.error(f"Exception: {e}")
def delete(id):
try:
return Results.mycol.delete_one({"_id": id})
except Exception as e:
log.error("Error occured in Results delete")
log.error(f"Exception: {e}")
def deleteMany(query):
try:
return Results.mycol.delete_many(query).acknowledged
except Exception as e:
log.error("Error occured in Results deleteMany")
log.error(f"Exception: {e}") |