I have a fairly large multi page app, and a postgres database, both hosted on azure. I am currently connecting to my database using sqlalchemy in a data_connections.py file somewhat like this:
engine = sqlalchemy.create_engine(new_db_url, connect_args={"sslmode": "require"})
Session = sqlalchemy.orm.sessionmaker(bind=engine)
and everywhere else in my app I connect to my database I import either engine or Session and connect.
However, I have read a lot about connecting my postgres database directly to the Flask server using flask_sqlalchemy.
I have been able to test connecting the database and server in a separate repo, using code that looks like this:
app, server = create_app()
# connect database to app
postgresURL = os.environ.get("GEORGIA_POSTGRES_URL")
app.server.config["SQLALCHEMY_DATABASE_URI"] = postgresURL
# necessary to suppress warning when using flask_sqlalchemy
app.server.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
db = SQLAlchemy(app.server)
if __name__ == "__main__":
# Initialise app and server
app.run(debug=True)
server = app.server
This appears to be connecting to the database correctly, but I am struggling to find more literature about connection best practices after this.
Should I import db.engine/db.session from this module in every module I will be connecting to my db in? If I import db everywhere I need, do I still gain much by doing all of this? Is it worth moving away from the connection method that I currently have, and if so why and what are the best practices for doing so?
Thank you!