Commit d6f58ffd authored by vipul.v's avatar vipul.v

aggregate functions

parents
#mongodb
MONGO_URI=mongodb://intern_23:intern%40123@192.168.0.220:2717/?authSource=interns_b2_23&authMechanism=SCRAM-SHA-256
\ No newline at end of file
# Default ignored files
/shelf/
/workspace.xml
<component name="InspectionProjectProfileManager">
<profile version="1.0">
<option name="myName" value="Project Default" />
<inspection_tool class="PyPep8NamingInspection" enabled="true" level="WEAK WARNING" enabled_by_default="true">
<option name="ignoredErrors">
<list>
<option value="N801" />
<option value="N803" />
</list>
</option>
</inspection_tool>
</profile>
</component>
\ No newline at end of file
<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.11 (mongodb-aggregation)" project-jdk-type="Python SDK" />
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/mongodb-aggregation.iml" filepath="$PROJECT_DIR$/.idea/mongodb-aggregation.iml" />
</modules>
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<module type="PYTHON_MODULE" version="4">
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$">
<excludeFolder url="file://$MODULE_DIR$/venv" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>
\ No newline at end of file
[SERVICE]
port=7999
host=0.0.0.0
[MONGO-DB]
mongo_uri=$MONGO_URI
\ No newline at end of file
from dotenv import load_dotenv
load_dotenv()
import uvicorn
from fastapi import FastAPI
from script.config.app_confing import Service
from script.service.inventory import router
app = FastAPI(title="Inventor Mt")
app.include_router(router)
if __name__ == "__main__":
uvicorn.run("main:app", host=Service.host, port=Service.port)
import pymongo
client = pymongo.MongoClient(
"mongodb://intern_23:intern%40123@192.168.0.220:2717/?authSource=interns_b2_23&authMechanism=SCRAM-SHA-256")
db = client["interns_b2_23"]
col = db["Vipul-inventory2"]
r = col.find()
print(list(r))
import os
from configparser import SafeConfigParser
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)
class APIEndpoints:
delete = "/delete"
save = "/save"
inventory_base = "/inventory"
insert = "/insert"
update = "/update"
find = "/find"
date = "/date"
aggregate = "/aggregate/{order_id}"
\ No newline at end of file
from script.config.app_confing import Mongo
from script.utils.mongo_utils import MongoConnect
mongo_client = MongoConnect(uri=Mongo.mongo_uri)()
from script.utils.mongo_utils import MongoCollectionBaseClass
class InventoryCollection(MongoCollectionBaseClass):
def __init__(self, mongo_client):
super().__init__(mongo_client=mongo_client, database="interns_b2_23", collection="Vipul-inventory2")
def insert_item(self, data):
self.insert_one(data)
class NameDoesNotExist(Exception):
pass
\ No newline at end of file
# class for CRUD operations
from datetime import datetime
from script.core.db.mongo.interns2023 import mongo_client
from script.core.db.mongo.interns2023.inventory import InventoryCollection
from script.core.schema.inventory import Inventory
class InventoryData:
def __init__(self):
self.inventory_col = InventoryCollection(mongo_client=mongo_client)
def insert_data(self, request_data: Inventory):
try:
d = {"order_id": request_data.order_id,
"customer_name": request_data.customer_name,
"date": datetime.now(),
"status": request_data.status,
"sales_order": request_data.sales_order}
self.inventory_col.insert_one(d)
except Exception as e:
print(e, "Error Detected in inserting")
def aggregate_data(self, order_id):
try:
pipeline = [
{
"$match":
{
"order_id": order_id,
},
},
{
"$sort":
{
"customer_name": -1,
},
},
{
"$limit": 2
},
{
"$project":
{
"customer_name": "$customer_name",
"_id": 0,
}
}
]
data = self.inventory_col.aggregate(pipeline)
list_ = []
for i in data:
list_.append(i)
return list_
except Exception as e:
print(e)
import datetime
from typing import Optional, Any
from pydantic import BaseModel
# define a model for Item
class Inventory(BaseModel):
order_id: int
customer_name: str
status: Optional[str]
sales_order: Optional[int]
from typing import Any, Optional
from pydantic import BaseModel
class DefaultResponse(BaseModel):
status: str = "failed"
message: str
data: Optional[Any]
import logging
from fastapi.routing import APIRouter
from script.constants import APIEndpoints
from script.core.handlers.inventory import InventoryData
from script.core.schema.inventory import Inventory
from script.core.schema.responses import DefaultResponse
router = APIRouter(prefix=APIEndpoints.inventory_base)
handler = InventoryData()
@router.post(APIEndpoints.insert)
async def insert_item(request_data: Inventory):
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(order_id: int):
try:
data = handler.aggregate_data(order_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="inserted Failed due to server error")
\ No newline at end of file
from fastapi import APIRouter
from pymongo import MongoClient
from script.config.app_confing 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