Почему БД не связана со значениемPython

Программы на Python
Anonymous
Почему БД не связана со значением

Сообщение Anonymous »

Это код для менеджера инвентаря. Я запустил API, проверил, работает ли он, а затем запустил тестовый файл. Я получаю внутренние ошибки сервера: говорится, что база данных не связана со значением, но это так.
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

Кажется, все в порядке, но я получаю эту обратную связь в терминале uvicorn:
ERROR: Exception in ASGI application
Traceback (most recent call last):
File "C:\Users\Rayaans Laptop\AppData\Local\Programs\Python\Python312\Lib\site-packages\uvicorn\protocols\http\h11_impl.py", line 408, in run_asgi
result = await app( # type: ignore[func-returns-value]
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Rayaans Laptop\AppData\Local\Programs\Python\Python312\Lib\site-packages\uvicorn\middleware\proxy_headers.py", line 84, in __call__
return await self.app(scope, receive, send)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Rayaans Laptop\AppData\Local\Programs\Python\Python312\Lib\site-packages\fastapi\applications.py", line 1106, in __call__
await super().__call__(scope, receive, send)
File "C:\Users\Rayaans Laptop\AppData\Local\Programs\Python\Python312\Lib\site-packages\starlette\applications.py", line 122, in __call__
await self.middleware_stack(scope, receive, send)
File "C:\Users\Rayaans Laptop\AppData\Local\Programs\Python\Python312\Lib\site-packages\starlette\middleware\errors.py", line 184, in __call__
raise exc
File "C:\Users\Rayaans Laptop\AppData\Local\Programs\Python\Python312\Lib\site-packages\starlette\middleware\errors.py", line 162, in __call__
await self.app(scope, receive, _send)
File "C:\Users\Rayaans Laptop\AppData\Local\Programs\Python\Python312\Lib\site-packages\starlette\middleware\exceptions.py", line 79, in __call__
raise exc
File "C:\Users\Rayaans Laptop\AppData\Local\Programs\Python\Python312\Lib\site-packages\starlette\middleware\exceptions.py", line 68, in __call__
await self.app(scope, receive, sender)
File "C:\Users\Rayaans Laptop\AppData\Local\Programs\Python\Python312\Lib\site-packages\fastapi\middleware\asyncexitstack.py", line 20, in __call__
raise e
File "C:\Users\Rayaans Laptop\AppData\Local\Programs\Python\Python312\Lib\site-packages\fastapi\middleware\asyncexitstack.py", line 17, in __call__
await self.app(scope, receive, send)
File "C:\Users\Rayaans Laptop\AppData\Local\Programs\Python\Python312\Lib\site-packages\starlette\routing.py", line 718, in __call__
await route.handle(scope, receive, send)
File "C:\Users\Rayaans Laptop\AppData\Local\Programs\Python\Python312\Lib\site-packages\starlette\routing.py", line 276, in handle
await self.app(scope, receive, send)
File "C:\Users\Rayaans Laptop\AppData\Local\Programs\Python\Python312\Lib\site-packages\starlette\routing.py", line 66, in app
response = await func(request)
^^^^^^^^^^^^^^^^^^^
File "C:\Users\Rayaans Laptop\AppData\Local\Programs\Python\Python312\Lib\site-packages\fastapi\routing.py", line 264, in app
solved_result = await solve_dependencies(
^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Rayaans Laptop\AppData\Local\Programs\Python\Python312\Lib\site-packages\fastapi\dependencies\utils.py", line 595, in solve_dependencies
solved = await solve_generator(
^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Rayaans Laptop\AppData\Local\Programs\Python\Python312\Lib\site-packages\fastapi\dependencies\utils.py", line 520, in solve_generator
return await stack.enter_async_context(cm)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Rayaans Laptop\AppData\Local\Programs\Python\Python312\Lib\contextlib.py", line 647, in enter_async_context
result = await _enter(cm)
^^^^^^^^^^^^^^^^
File "C:\Users\Rayaans Laptop\AppData\Local\Programs\Python\Python312\Lib\contextlib.py", line 204, in __aenter__
return await anext(self.gen)
^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Rayaans Laptop\AppData\Local\Programs\Python\Python312\Lib\site-packages\fastapi\concurrency.py", line 36, in contextmanager_in_threadpool
raise e
UnboundLocalError: cannot access local variable 'db' where it is not associated with a value

вот код внутри 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()


Подробнее здесь: https://stackoverflow.com/questions/787 ... th-a-value

Вернуться в «Python»