Reputation: 162
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
Upvotes: 4
Views: 3673
Reputation: 9568
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 have 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 (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 both 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 (e.g. 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.
Upvotes: 5