这是库存管理器的代码,我启动了API,检查它是否已启动,然后运行测试文件。我一直收到内部服务器错误,它说 db 与值没有关联,但它确实与值关联。
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()
我只需要更改一个小写字母大小写,类
db
正在干预变量db
,我更改了systemfiles.db to systemfiles.Db
。有时这些小错误很难识别。