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
app.app_context() and db.create_all() in __init__.py are used to create the Postgres database if it doesn't already exist and to be able to make session calls such as db.session.commit(). In other words, app.app_context() and db.create_all() are used to establish the connection to Postgres.
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import func, exc
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():
try:
db.create_all()
except exc.SQLAlchemyError as sqlalchemyerror:
print(sqlalchemyerror)
except Exception as exception:
print(exception)
finally:
print("no exceptions were raised")
return app
Did you find this article helpful?
If so, consider buying me a coffee over at