I learned something about using Python today, and this might influence how I write other parts of my code. I'm also open to ideas on the best way to go about this.
I'm now most of the way through a refactor where I'm switching to Postgres for my database and also using SQLModel over SQLAlchemy. I have all my classes written/rewritten and was running into an issue on the IPAM side of things when creating a new network. See if you can spot the bug as I write it out here.
Each API call in FastAPI will map to one function, with each class having their functions in their own file, for the sake of modularity/organization. I have a subnet.py file and ipRecords.py for those respective classes.
When a new subnet is created, I make the subnet in the database and then populate all of the IP addresses in the IpAddress table before returning to the FastAPI call. This means that one function call is chained to another one. Specifically subnet.createSubnet calls Iprecords.createIpRecord.
Both functions have a Session object coming in like this. Note that Depends comes from SQLModel and getDb() returns a database session, via yield.
myFunction( input1: int, input2, str, db: Session = Depends(getDb))
This means that when a new subnet is added, and then we call iprecords.createIpRecord, that doesn't get the proper result for getDb and we can't talk to the database.
My fix was to pass the db from one function to another so I can keep using it, and not pull it in via getDb on the inner function call.
Now that I'm through that mess, I can carry on with the rest of my refactor and get back to the main branch.
#pebkac #rackroot #programming #fastapi #python #ipam #homelab #opensource #sqlmodel