Commit 5411e03c authored by vidya.m's avatar vidya.m

firstcommit

parents
client = mongodb://intern_23:intern%40123@192.168.0.220:2717/?serverSelectionTimeoutMS=5000&connectTimeoutMS=10000&authSource=interns_b2_23&authMechanism=SCRAM-SHA-256
\ No newline at end of file
# Default ignored files
/shelf/
/workspace.xml
<component name="InspectionProjectProfileManager">
<settings>
<option name="USE_PROJECT_PROFILE" value="false" />
<version value="1.0" />
</settings>
</component>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectRootManager" version="2" project-jdk-name="Python 3.10 (mongo_agg)" project-jdk-type="Python SDK" />
</project>
\ No newline at end of file
[SERVICE]
port=7998
host=0.0.0.0
[MONGO-DB]
mongo_uri=$MONGO_URI
from dotenv import load_dotenv
load_dotenv()
import uvicorn
from fastapi import FastAPI
from scripts.config.app_config import Service
from scripts.service.agg import router
app = FastAPI(title="Student Management System")
app.include_router(router)
if __name__ == "__main__":
uvicorn.run("main:app", host=Service.host, port=Service.port)
\ No newline at end of file
import pymongo
client = pymongo.MongoClient('mongodb://intern_23:intern%40123@192.168.0.220:2717/?serverSelectionTimeoutMS=5000&connectTimeoutMS=10000&authSource=interns_b2_23&authMechanism=SCRAM-SHA-256')
db = client['interns_b2_23']
collection = db['student']
r = collection.find()
print(list(r))
\ No newline at end of file
from configparser import SafeConfigParser
import os
config = SafeConfigParser()
config.read('conf/application.conf')
class Service:
port = int(config.getint("SERVICE", "port"))
host = config.get("SERVICE", "host")
class Mongo:
mongo_uri:str = os.environ.get("MONGO_URI")
print(mongo_uri)
\ No newline at end of file
class APIEndpoints:
delete = "/delete"
save = "/save"
student_base = "/student"
insert = "/insert"
update = "/update"
find = "/find"
date = "/date"
aggregate = "/aggregate/{stud_id}"
\ No newline at end of file
from scripts.config.app_config import Mongo
from scripts.utils.mongo_util import MongoConnect
mongo_client = MongoConnect(uri=Mongo.mongo_uri)()
from scripts.utils.mongo_util import MongoCollectionBaseClass
class StudentCollection(MongoCollectionBaseClass):
def __init__(self, mongo_client):
super().__init__(mongo_client=mongo_client, database="interns_b2_23", collection="student")
def insert_item(self, data):
self.insert_one(data)
class NameDoesNotExist(Exception):
pass
\ No newline at end of file
from datetime import datetime
from scripts.core.db.mongo.interns2023 import mongo_client
from scripts.core.db.mongo.interns2023.agg import StudentCollection
from scripts.core.schema.agg import Student
class StudentData:
def __init__(self):
self.student_col = StudentCollection(mongo_client=mongo_client)
def insert_data(self, request_data: Student):
try:
d = {"stud_id": request_data.stud_id,
"stud_name": request_data.stud_name,
"dateofadmission": datetime.now(),
"status": request_data.status,
"city": request_data.city}
self.student_col.insert_one(d)
except Exception as e:
print(e, "Error Detected in inserting")
def aggregate_data(self, stud_id):
try:
pipeline = [
{
"$match":
{
"stud_id": stud_id,
},
},
{
"$sort":
{
"stud_name": -1,
},
},
{
"$limit": 5
},
{
"$project":
{
"stud_name": "$stud_name",
"_id": 0,
}
}
]
data = self.student_col.aggregate(pipeline)
list_ = []
for i in data:
list_.append(i)
return list_
except Exception as e:
print(e)
\ No newline at end of file
import datetime
from typing import Optional, Any
from pydantic import BaseModel
# define a model for Item
class Student(BaseModel):
stud_id: int
stud_name: str
status: Optional[str]
city: Optional[str]
from typing import Any, Optional
from pydantic import BaseModel
class DefaultResponse(BaseModel):
status: str = "failed"
message: str
data: Optional[Any]
\ No newline at end of file
import logging
from fastapi.routing import APIRouter
from scripts.constants import APIEndpoints
from scripts.core.handlers.agg import StudentData
from scripts.core.schema.agg import Student
from scripts.core.schema.responses import DefaultResponse
router = APIRouter(prefix=APIEndpoints.student_base)
handler = StudentData()
@router.post(APIEndpoints.insert)
async def insert_item(request_data: Student):
try:
handler.insert_data(request_data)
return DefaultResponse(message="Successfully inserted", status="success")
except ValueError:
return DefaultResponse(message="Due to value error")
except Exception as e:
logging.exception(e)
return DefaultResponse(message="inserted Failed due to server error")
@router.get(APIEndpoints.aggregate)
async def aggregate_item(stud_id: int):
try:
data = handler.aggregate_data(stud_id)
return DefaultResponse(message="Successfully found", status="success", data=data)
except ValueError:
return DefaultResponse(message="Due to value error")
except Exception as e:
logging.exception(e)
return DefaultResponse(message="Failed due to server error")
\ No newline at end of file
from fastapi import APIRouter
from pymongo import MongoClient
from scripts.config.app_config import Mongo
router = APIRouter()
# Create a MongoClient instance
client = MongoClient(Mongo.mongo_uri)
# Connect to a database
db = client.mydatabase
\ No newline at end of file
import logging
from typing import Dict, List
from pymongo import MongoClient
class MongoConnect:
def __init__(self, uri):
try:
self.uri = uri
self.client = MongoClient(self.uri, connect=False)
except Exception as e:
logging.error(f"Exception in connection {(str(e))}")
raise e
def __call__(self, *args, **kwargs):
return self.client
def __repr__(self):
return f"Mongo Client(uri:{self.uri}, server_info={self.client.server_info()})"
class MongoCollectionBaseClass:
def __init__(self, mongo_client, database, collection):
self.client = mongo_client
self.database = database
self.collection = collection
def __repr__(self):
return f"{self.__class__.__name__}(database={self.database}, collection={self.collection})"
def insert_one(self, data: Dict):
try:
database_name = self.database
collection_name = self.collection
db = self.client[database_name]
collection = db[collection_name]
response = collection.insert_one(data)
return response.inserted_id
except Exception as e:
logging.error(f"Error in inserting the data {str(e)}")
raise e
def aggregate(self, pipeline: List):
try:
database_name = self.database
collection_name = self.collection
db = self.client[database_name]
collection = db[collection_name]
response = collection.aggregate(pipeline)
return response
except Exception as e:
logging.error(f"Error in inserting the data {str(e)}")
raise e
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment