This is the code for an inventory manager, I started the API, checked if it was up, than ran a test file. I have been geting internal server errors, it’s saying db is not associated with a value but it is.
from fastapi import FastAPI, HTTPException, Depends
from systemfiles import db, models, schemas
app = FastAPI()
# Dependency injection for database session
def get_db():
db = db.SessionLocal()
try:
yield db
finally:
db.close()
@app.get("/products/", response_model=list[schemas.product])
async def get_products(db: db.SessionLocal = Depends(get_db)):
products = db.query(models.Product).all()
return products
@app.post("/products/", response_model=schemas.product, status_code=201)
async def create_product(product: schemas.ProductCreate, db: db.SessionLocal = Depends(get_db)):
db_product = models.Product(**product.model_dump())
db.add(db_product)
db.commit()
db.refresh(db_product)
return db_product
@app.get("/products/{product_id}", response_model=schemas.product)
async def get_product(product_id: int, db: db.SessionLocal = Depends(get_db)):
product = db.query(models.Product).filter(models.Product.id == product_id).first()
if not product:
raise HTTPException(status_code=404, detail="Product not found")
return product
everything seems ok but i have been getting this traceback in the uvicorn terminal :
ERROR: Exception in ASGI application
Traceback (most recent call last):
File "C:UsersRayaans LaptopAppDataLocalProgramsPythonPython312Libsite-packagesuvicornprotocolshttph11_impl.py", line 408, in run_asgi
result = await app( # type: ignore[func-returns-value]
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:UsersRayaans LaptopAppDataLocalProgramsPythonPython312Libsite-packagesuvicornmiddlewareproxy_headers.py", line 84, in __call__
return await self.app(scope, receive, send)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:UsersRayaans LaptopAppDataLocalProgramsPythonPython312Libsite-packagesfastapiapplications.py", line 1106, in __call__
await super().__call__(scope, receive, send)
File "C:UsersRayaans LaptopAppDataLocalProgramsPythonPython312Libsite-packagesstarletteapplications.py", line 122, in __call__
await self.middleware_stack(scope, receive, send)
File "C:UsersRayaans LaptopAppDataLocalProgramsPythonPython312Libsite-packagesstarlettemiddlewareerrors.py", line 184, in __call__
raise exc
File "C:UsersRayaans LaptopAppDataLocalProgramsPythonPython312Libsite-packagesstarlettemiddlewareerrors.py", line 162, in __call__
await self.app(scope, receive, _send)
File "C:UsersRayaans LaptopAppDataLocalProgramsPythonPython312Libsite-packagesstarlettemiddlewareexceptions.py", line 79, in __call__
raise exc
File "C:UsersRayaans LaptopAppDataLocalProgramsPythonPython312Libsite-packagesstarlettemiddlewareexceptions.py", line 68, in __call__
await self.app(scope, receive, sender)
File "C:UsersRayaans LaptopAppDataLocalProgramsPythonPython312Libsite-packagesfastapimiddlewareasyncexitstack.py", line 20, in __call__
raise e
File "C:UsersRayaans LaptopAppDataLocalProgramsPythonPython312Libsite-packagesfastapimiddlewareasyncexitstack.py", line 17, in __call__
await self.app(scope, receive, send)
File "C:UsersRayaans LaptopAppDataLocalProgramsPythonPython312Libsite-packagesstarletterouting.py", line 718, in __call__
await route.handle(scope, receive, send)
File "C:UsersRayaans LaptopAppDataLocalProgramsPythonPython312Libsite-packagesstarletterouting.py", line 276, in handle
await self.app(scope, receive, send)
File "C:UsersRayaans LaptopAppDataLocalProgramsPythonPython312Libsite-packagesstarletterouting.py", line 66, in app
response = await func(request)
^^^^^^^^^^^^^^^^^^^
File "C:UsersRayaans LaptopAppDataLocalProgramsPythonPython312Libsite-packagesfastapirouting.py", line 264, in app
solved_result = await solve_dependencies(
^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:UsersRayaans LaptopAppDataLocalProgramsPythonPython312Libsite-packagesfastapidependenciesutils.py", line 595, in solve_dependencies
solved = await solve_generator(
^^^^^^^^^^^^^^^^^^^^^^
File "C:UsersRayaans LaptopAppDataLocalProgramsPythonPython312Libsite-packagesfastapidependenciesutils.py", line 520, in solve_generator
return await stack.enter_async_context(cm)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:UsersRayaans LaptopAppDataLocalProgramsPythonPython312Libcontextlib.py", line 647, in enter_async_context
result = await _enter(cm)
^^^^^^^^^^^^^^^^
File "C:UsersRayaans LaptopAppDataLocalProgramsPythonPython312Libcontextlib.py", line 204, in __aenter__
return await anext(self.gen)
^^^^^^^^^^^^^^^^^^^^^
File "C:UsersRayaans LaptopAppDataLocalProgramsPythonPython312Libsite-packagesfastapiconcurrency.py", line 36, in contextmanager_in_threadpool
raise e
UnboundLocalError: cannot access local variable 'db' where it is not associated with a value
heres the code inside systemfiles/db.py:
from sqlalchemy import create_engine, Column, Integer, String, Float
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
# Create the database engine
engine = create_engine("sqlite:///inventory.db")
# Create a SessionLocal class for creating database sessions
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
# Create a base class for declarative models
Base = declarative_base()
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()