rohanshaw's picture
Upload 8 files
cfd8098 verified
from motor.motor_asyncio import AsyncIOMotorClient
from pydantic import BaseModel, Field
from pydantic_core import CoreSchema, PydanticCustomError, core_schema
import os
from dotenv import load_dotenv
# Load environment variables from .env file
load_dotenv()
# --- Configuration ---
# Example: MONGODB_URI = "mongodb+srv://<user>:<password>@cluster0.xyz.mongodb.net/"
MONGODB_URI = os.getenv("MONGODB_URI", "")
DB_NAME = "hf_masala_barcodes"
# --- Database Client ---
client = AsyncIOMotorClient(MONGODB_URI)
db = client[DB_NAME] # Database: hf_masala_barcodes
# --- Collections ---
# We access the database collections here
user_collection = db.get_collection("users")
sku_collection = db.get_collection("skus")
# This helps FastAPI validate data from MongoDB and is now fully V2 compliant.
class PyObjectId(str):
"""Custom type to handle MongoDB ObjectId for Pydantic V2.
It serializes MongoDB ObjectIds (or their string representations) as strings
for JSON serialization and validation.
"""
@classmethod
def __get_pydantic_core_schema__(cls, source_type, handler) -> CoreSchema:
# Define the validation logic
def validate_object_id(value):
"""Converts the input (e.g., an ObjectId object) into a string."""
try:
# We return the string representation of the ID
return str(value)
except Exception:
raise PydanticCustomError('invalid_objectid', 'ObjectId or string representation required')
# Fix: Changed core_schema.string_schema() to core_schema.str_schema()
string_schema = core_schema.str_schema()
# Define the core schema for the type
return core_schema.json_or_python_schema(
json_schema=string_schema,
python_schema=core_schema.chain_schema([
# Accept any type (e.g., a bson.ObjectId instance)
core_schema.any_schema(),
# Use our custom validator function
core_schema.no_info_plain_validator_function(validate_object_id),
]),
# Ensure the final output (for serialization) is a string
serialization=core_schema.to_string_ser_schema(),
)