Bootstrap FreeKB - Flask - Connect to Postgres using SQLAlchemy create_engine
Flask - Connect to Postgres using SQLAlchemy create_engine

Updated:   |  Flask articles

If you are not familiar with SQLAlchemy, check out my article Getting Started with SQLAlchemy.

Flask uses the MVC (Model View Controller) Framework. Just to make this as obvious as possible, I like my Flask apps to have the following.

  • Model -> models.py
  • View -> views.py
  • Controller -> __init__.py

And let's say your Flask app has the following structure.

├── main.py
├── database (directory)
│   ├── example.db
├── my-project (directory)
│   ├── __init__.py
│   ├── views.py
│   ├── models.py
│   ├── templates (directory)
│   │   ├── base.html
│   │   ├── home.html
│   │   ├── results.html
│   └── static (directory)
│       └── custom.css

 

You will need to install the psycopg module to be able to make the connection to Postgres.

pip install flask-sqlalchemy
pip install psycopg2

 

Or, you can specify the version to install

pip install flask-sqlalchemy==3.0.5
pip install psycopg2==2.9.6

 

Or, better yet, use a requirements.txt file.

flask-sqlalchemy==3.0.5
psycopg2==2.9.6

 

And then install the packages using the requirements.txt file.

pip install --requirement requirements.txt

 

create_engine(uri) can be used to make the connection to Postgres. In this example, create_engine(uri) is in __init__.py.

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import create_engine

db = SQLAlchemy()

def app_obj():
    app = Flask(__name__)
    uri = 'postgresql+psycopg2://johndoe:itsasecret@10.21.50.198:5432/mydb'
    app.config['SQLALCHEMY_DATABASE_URI'] = uri
    app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
    db.init_app(app)

    with app.app_context():
        db.create_engine(uri)

    return app

 

And then your view, such as views.py, engine.connect() can be used to test the connection to Postgres.

from flask import Blueprint
from . import app, db
from sqlalchemy import exc

views = Blueprint('views', __name__)

@views.route('/')
def home():
    try:
        db.engine.connect()
    except exc.SQLAlchemyError as sqlalchemyerror:
        return sqlalchemyerror
    except Exception as exception:
        return exception
    else:
        return "no exceptions were raised - it appears the connection to Postgres was successful"

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter 87467b in the box below so that we can be sure you are a human.