I am trying to find the right way to connect a PostgreSQL database to my flaks app that is separated in blueprints without using SQLalchemy. I have found similar answers, but none are in my situation. Thank you!
-
What do you mean by not using SQLalchemy? Does it mean you do not want to use the library at all or you don't want to use the SQLAlchemy models?Kartikeya Sharma– Kartikeya Sharma2022-10-17 22:29:09 +00:00Commented Oct 17, 2022 at 22:29
-
Sorry for not specifying. I really don't like the model system. I don't have any technical limitations, I could use it.HCook886– HCook8862022-10-18 05:04:24 +00:00Commented Oct 18, 2022 at 5:04
-
If you don't like the model system then you can easily use the structure I have given below!Kartikeya Sharma– Kartikeya Sharma2022-10-21 18:20:44 +00:00Commented Oct 21, 2022 at 18:20
2 Answers
I will do something like this:
The structure of the application will look like this:
├── application # hosts the application
│ ├── __init__.py
│ ├── blueprint1
│ ├── blueprint2
├── application.py # contains the actual python code that will import the app
└── config.py
Now inside your init.py, you can create the database connection like this
from flask import Flask
import psycopg2
db_connection = psycopg2.connect("dbname=suppliers user=postgres password=postgres")
def create_app(config_class=Config):
application = Flask(__name__)
application.config.from_object(config_class)
# register blueprints here
from application.blueprint1 import bp as blueprint1_bl
application.register_blueprint(main_blueprint, url_prefix="/")
from application.blueprint2 import bp as blueprint2_bl
application.register_blueprint(
blueprint2_bl, url_prefix="/bl2"
)
return application
And now let's say you have to access it from blueprint1 and blueprint1 is a separate directory. Then I will have a directory structure for each blueprint as below:
├── blueprint1 /
| ├── __init__.py
| └── static/blueprint1/
| └── templates/blueprint1/
| └── routes.py
Now from your routes.py file you can access the database connection as below:
from application import db_connection
from application.blueprint1 import bp
@bp.route("/", methods=["GET"])
def bl1_page():
"""It renders bl1 Page."""
cursor = connection.cursor()
postgreSQL_select_Query = "select * from mobile"
cursor.execute(postgreSQL_select_Query)
print("Selecting rows from mobile table using cursor.fetchall")
mobile_records = cursor.fetchall()
print("Print each row and it's columns values")
for row in mobile_records:
print("Id = ", row[0], )
print("Model = ", row[1])
print("Price = ", row[2], "\n")
return render_template(
"blueprint1/blueprint1.html"
)
And if you don't know how init.py file inside the blueprint will look like, it would look something like this
from flask import Blueprint
bp = Blueprint(
"blueprint1",
__name__,
template_folder="templates",
static_folder="static",
static_url_path="/blueprint1/static",
)
from application.blueprint1 import routes
Comments
https://github.com/thefcraft/flask_postgresql
# pip install flask-pgsql --user
from flask_postgresql import PostgreSQL
db = PostgreSQL(hostname=hostname, port=port, database=database, username=username, password=password)
class Test(db.Model):
id = db.Column(db.Integer, primary_key=True)
data = db.Column(db.Integer, array=True)
def __repr__(self):
return f"Test({self.id}, {self.data})"
if __name__ == "__main__":
if RESET:
db.create_all() # with app.app_context(): db.create_all() will also work
p = Test(data = [21, 24])
db.session.add(p)
db.session.commit()
Test.query.get(id=1).data #-> [21, 24]