sarva-ai-back / main.py
navpan2's picture
Create main.py
f44e85b verified
raw
history blame
2.02 kB
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from motor.motor_asyncio import AsyncIOMotorClient
from typing import List, Optional
from fastapi.middleware.cors import CORSMiddleware
# MongoDB connection URI
MONGO_URI = "mongodb+srv://npanchayan:ramnagar@cluster0.7stwm.mongodb.net/?retryWrites=true&w=majority&appName=Cluster0"
# Initialize FastAPI app
app = FastAPI()
# Allow CORS for all origins
app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # Allows all origins, change this to more specific if needed
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# MongoDB client
client = AsyncIOMotorClient(MONGO_URI)
db = client.disease # MongoDB database
disease_collection = db.diseases # MongoDB collection
# Pydantic model to represent the Disease schema
class Disease(BaseModel):
diseaseName: str
description: str
cause: str
symptoms: List[str]
treatments: List[str]
preventionTips: Optional[List[str]] = []
imageURL: Optional[str] = None
createdAt: str
# API endpoint to fetch disease details by name
@app.get("/disease/{name}", response_model=Disease)
async def get_disease(name: str):
# Fetch the disease from MongoDB
disease = await disease_collection.find_one({"diseaseName": name})
if disease is None:
raise HTTPException(status_code=404, detail="Disease not found")
# Convert MongoDB document to Pydantic model
disease_data = Disease(
diseaseName=disease["diseaseName"],
description=disease["description"],
cause=disease["cause"],
symptoms=disease["symptoms"],
treatments=disease["treatments"],
preventionTips=disease.get("preventionTips", []),
imageURL=disease.get("imageURL", None),
createdAt=disease["createdAt"].isoformat(),
)
return disease_data
# Run the FastAPI server using Uvicorn
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=5000)