I've been searching StackOverflow questions and reading SQLAlchemy and Flask-SQLAlchemy docs, and have still not figured out how to get reflection working (still new to SQLAlchemy).
When I try to map the table using the engine, I get the error "sqlalchemy.exc.ArgumentError: Mapper Mapper|User|user could not assemble any primary key columns for mapped table 'user'". In spite of that, user has column 'id' as a primary key in the database. I'm not sure if there's something else I need to do here first. I had thought that if I could reflect, it would automatically give my User model class properties named after the database columns, and I wouldn't have to define them manually.
Here is my code that I've cobbled together so far:
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.orm import mapper
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = "mysql+pymysql://" + dbUser + ":" + dbPass + "@" + dbAddress + ":3306/" + dbName
app.config["SQLALCHEMY_ECHO"] = True
db = SQLAlchemy(app)
engine = db.engine
meta = db.metadata
Now with that, I know that db will give me a good database session. I'm not sure yet about what I'm doing wrong with engine and meta. I've seen engine being used to create the context differently, but I think I'm creating that with this line (from above):
db = SQLAlchemy(app)
Here's the place where I'm trying to reflect a model class: class User(db.Model): try: self = db.Model.metadata.tables('user', metadata) #self = Tadb.Model.metadata.tables('user', meta, autoload=True, autoload_with=engine, extend_existing=True) #Table('user', metadata, autoload_with=engine, extend_existing=True) #self = Table('user', meta, autoload_with=engine, extend_existing=True) #self.metadata.reflect(extend_existing=True, only=['user']) except Exception as e: print("In init User(): failed to map table user - " + str(e))
I get the mapper error on this line (from above): self = db.Model.metadata.tables('user', metadata) I've tried the other lines as well, but it doesn't seem to know what Table is...I have Flask-SQLAlchemy 2.3.2.
Am I making any obvious mistakes here?
Aucun commentaire:
Enregistrer un commentaire