In SQLAlchemy, creating engine, metadata and table in a loop creates DuplicateTable error

Viewed 38

In FastAPI / SqlAlchemy I want to create engines and corresponding metadata and tables in a loop:

from sqlalchemy import Column, Integer, String, create_engine, MetaData, Table
from fastapi import FastAPI

all_db_tables = [
    {
        "db" : "collector",
        "table" : "new_table",
    },
    {
        "db" : "collector2",
        "table" : "new_table2",
    }
]


alls = {}

for db_table in all_db_tables:

    tmp_engine = create_engine("postgresql://postgres:f7Af&JhyuqdD@localhost/"+db_table["db"])  
    tmp_meta = MetaData(tmp_engine)
    table_tmp = Table(
        db_table["table"],
        tmp_meta,
        Column("id", Integer, primary_key=True),
        Column("computername", String),
    )

    table_tmp.create()

app = FastAPI()

But I get this error:

sqlalchemy.exc.ProgrammingError: (psycopg2.errors.DuplicateTable) ERREUR: relation « new_table » already exists

[SQL: CREATE TABLE new_table ( id SERIAL NOT NULL, computername VARCHAR, PRIMARY KEY (id) ) ]

0 Answers
Related