In FastAPI, I need to dynamically connect to a database after a POST request, i.e, in the POST request body, I receive database_name on which I need to connect.
So I have tried this:
import databases
@app.post("/computers/", response_model=Computer)
async def create_computer(computer: ComputerIn):
DATABASE_URL = "postgresql://username:password@localhost/"+computer.database_name
database = databases.Database(DATABASE_URL)
database.connect()
...
But I get the following error:
File "/home/.local/lib/python3.8/site-packages/databases/backends/postgres.py", line 169, in acquire assert self._database._pool is not None, "DatabaseBackend is not running" AssertionError: DatabaseBackend is not running
Any idea why this might not work ?
Thanks
Two things:
await keyword. Here's an example taken from the github's page https://github.com/encode/databases# Create a database instance, and connect to it.
from databases import Database
database = Database('sqlite+aiosqlite:///example.db')
await database.connect()
# Create a table.
query = """CREATE TABLE HighScores (id INTEGER PRIMARY KEY, name VARCHAR(100), score INTEGER)"""
await database.execute(query=query)