Skip to content

Commit

Permalink
Error Handling for Unique Keys
Browse files Browse the repository at this point in the history
  • Loading branch information
VVoruganti committed May 9, 2024
1 parent 2e4702c commit edc6843
Show file tree
Hide file tree
Showing 4 changed files with 48 additions and 9 deletions.
25 changes: 23 additions & 2 deletions api/src/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

import sentry_sdk
from fastapi import APIRouter, FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import PlainTextResponse
from fastapi_pagination import add_pagination
from opentelemetry import trace
Expand Down Expand Up @@ -195,17 +196,37 @@ async def lifespan(app: FastAPI):
{"url": "http://127.0.0.1:8000", "description": "Local Development Server"},
{"url": "https:/demo.honcho.dev", "description": "Demo Server"},
],
title="Honcho API",
summary="An API for adding personalization to AI Apps",
description="""This API is used to store data and get insights about users for AI
applications""",
version="0.1.0",
title="Honcho API",
contact={
"name": "Plastic Labs",
"url": "https://plasticlabs.ai",
"email": "[email protected]",
},
license_info={
"name": "GNU Affero General Public License v3.0",
"identifier": "AGPL-3.0-only",
"url": "https://github.com/plastic-labs/honcho/blob/main/LICENSE",
},
)

origins = ["http://localhost", "http://127.0.0.1:8000", "https://demo.honcho.dev"]

app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)


if OPENTELEMTRY_ENABLED:
FastAPIInstrumentor().instrument_app(app)


router = APIRouter(prefix="/apps/{app_id}/users/{user_id}")

# Create a Limiter instance
Expand Down
14 changes: 12 additions & 2 deletions api/src/routers/apps.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@

import httpx
from fastapi import APIRouter, Depends, HTTPException, Request
from psycopg.errors import UniqueViolation
from sqlalchemy.exc import IntegrityError
from sqlalchemy.ext.asyncio import AsyncSession

from src import crud, schemas
Expand Down Expand Up @@ -89,8 +91,16 @@ async def create_app(
# if data:
# return honcho_app
# else:
honcho_app = await crud.create_app(db, app=app)
return honcho_app
try:
honcho_app = await crud.create_app(db, app=app)
return honcho_app

except IntegrityError as e:
raise HTTPException(
status_code=406, detail="App with name may already exist"
) from e
except Exception as e:
raise HTTPException(status_code=400, detail="Unknown Error") from e


@router.get("/get_or_create/{name}", response_model=schemas.App)
Expand Down
14 changes: 10 additions & 4 deletions api/src/routers/users.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,10 @@
import uuid
from typing import Optional

from fastapi import APIRouter, Depends, Request
from fastapi import APIRouter, Depends, HTTPException, Request
from fastapi_pagination import Page
from fastapi_pagination.ext.sqlalchemy import paginate
from sqlalchemy.exc import IntegrityError

from src import crud, schemas
from src.dependencies import db
Expand Down Expand Up @@ -36,7 +37,12 @@ async def create_user(
"""
print("running create_user")
return await crud.create_user(db, app_id=app_id, user=user)
try:
return await crud.create_user(db, app_id=app_id, user=user)
except IntegrityError as e:
raise HTTPException(
status_code=406, detail="User with name may already exist"
) from e


@router.get("", response_model=Page[schemas.User])
Expand Down Expand Up @@ -128,8 +134,8 @@ async def get_or_create_user(
"""
user = await crud.get_user_by_name(db, app_id=app_id, name=name)
if user is None:
user = await crud.create_user(
db, app_id=app_id, user=schemas.UserCreate(name=name)
user = await create_user(
request=request, db=db, app_id=app_id, user=schemas.UserCreate(name=name)
)
return user

Expand Down
4 changes: 3 additions & 1 deletion api/src/security.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,9 @@
USE_AUTH_SERVICE = os.getenv("USE_AUTH_SERVICE", "False").lower() == "true"
AUTH_SERVICE_URL = os.getenv("AUTH_SERVICE_URL", "http://localhost:8001")

security = HTTPBearer(auto_error=False)
security = HTTPBearer(
auto_error=False,
)


async def auth(
Expand Down

0 comments on commit edc6843

Please sign in to comment.