-
-
Notifications
You must be signed in to change notification settings - Fork 8.7k
Closed
Labels
Description
Example Code
def get_db_connection():
conn = pymssql.connect(
server=settings.server,
user=settings.user,
password=settings.password,
database=settings.database,
port=settings.port,
as_dict=True,
)
try:
yield conn
finally:
conn.close()
router = APIRouter(
prefix="/project",
tags=["project"],
dependencies=[Depends(get_db_connection)],
responses={418: {"description": "Project status API."}},
)
@router.get("/count/{status}")
def projects_count(
status: str, conn: pymssql.Connection = Depends(get_db_connection)
) -> dict:
try:
if status.upper() == "ALL":
status = None
return aq.get_project_count(conn, status=status)
except:
raise HTTPException(404, "Unable to get project count")Description
There are several endpoints in the router. And all of them have the parameter conn. Can I avoid declaring this parameter at each router by declaring it as the dependency at APIRouter? And how to access the dependency declared at APIRouter in a route?
Operating System
Linux
Operating System Details
No response
FastAPI Version
0.66.0
Python Version
3.9.6
Additional Context
When I did google search for the same, the following is what I get:
#424
https://stackoverflow.com/questions/63961339/how-to-access-route-dependencies-in-custom-apiroute-class
https://stackoverflow.com/questions/64506036/fastapi-how-to-access-attributes-of-class-based-dependency-inside-route-when-dep
Is there a simpler solution?
Reactions are currently unavailable