sqlalchemyfastapi

AssertionError: DatabaseBackend is not running


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


Solution

  • Two things:

    1. You forgot the 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)
    
    1. It is not good practice to connect to a database on every request. It is better to connect at runtime and then share the connection pool, so that at every request a new connection is not create. Instead, the currently active connection pool is used, wasting fewer resource. See https://fastapi.tiangolo.com/advanced/events/ for further information