I am trying to create a python web application that will connect to an existing sqlite database. Here is my code
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.ext.declarative import declarative_base
app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///history.db"
db = SQLAlchemy(app)
app.app_context().push()
db.reflect()
History = db.Table(
"history",
db.Model.metadata,
autoload=True,
autoload_with=db.engine
)
print(db.Table("history", db.Model.metadata).columns.items())
But this code generates the following error:
TypeError: Additional arguments should be named <dialectname>_<argument>, got 'autoload'
I can find documentation for loading an existing database schema with sqlalchemy
, but nothing for loading a database schema using flask_sqlalchemy
How do I load my sqlite database into a flask application using flask_sqlalchemy
?
Thanks to the reply from M69k65y
, I was finally able to solve this!
Updated code:
History = db.Table(
"history",
db.Model.metadata
autoload_with=db.engine
)
and this gave me an error:
sqlalchemy.exc.NoSuchTableError: history
I modified my connection URL to use an absolute path:
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///C:\\Projects\\HistoryDatabase\\history.db"
And I was finally able to get the table schema!
NOTE: I am using Python 3.8.10 on Windows 10
You don't need to include the argument autoload
.
As of SQLAlchemy 2.0, the autoload_with
argument should be used instead of autoload
. (See the
Your code would look like this:
History = db.Table(
"history",
db.Model.metadata,
autoload_with=db.engine
)