简体   繁体   中英

SqlAlchemy automap not generating Base.classes.[table_name]

I have an existing sqlite db file imported from csv. I tried to use sqlalchemy to automap the db file. But it always gives me...

Traceback (most recent call last): File "", line 1, in File "C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python36-32\\lib\\site-packages\\sqlalchemy\\util_colle ctions.py", line 212, in getattr raise AttributeError(key) AttributeError: destinationservices

Any help is appreciated.

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)

from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import Session
from sqlalchemy import create_engine

Base = automap_base()

# engine, suppose it has two tables 'user' and 'address' set up
engine = create_engine("sqlite:///destServ.db")

# reflect the tables
Base.prepare(engine, reflect=True)

# mapped classes are now created with names by default
# matching that of the table name.
Service = Base.classes.destinationServices

Forgive me answering an old question, but the reason this happens is because of limitations in the reflection capabilities, and it rears its head more often with SQLite databases because they are often over-simplified. To make automap_base work, you need to make sure your SQLite database tables has a primary key with a unique value (yes, this sounds redundant, but apparently they have different meanings in SQLite?).

If you are using DB Browser for SQLite ( https://sqlitebrowser.org/ -- works on Mac and Windows), you can click on the "Database Structure" tab, click on a table name, then a "Modify Table" sub-tab should become visible in the secondary tabs just below the main tabs (yes, the UI is a bit weird).

Once you're in the "Modify Table" popup window, find your table's primary key and make sure you check the PK and U boxes (for Primary Key and Unique). While you're in there, you can take the opportunity to make sure your columns have sensible types (eg make sure number columns use the proper numeric type). Click Ok when you're done.

Once your database is properly defined, print(Base.classes.keys()) should reveal all the tables in your database.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM