Best practices for persistent database connections in Python when using Flask Best practices for persistent database connections in Python when using Flask database database

Best practices for persistent database connections in Python when using Flask


Turns out there is a straightforward way to achieve what I was after. But as the commenters suggested, if it is at all possible to go the flask sqlalchemy route, then you might want to go that way. My approach to solving the problem is to save the connection object in a module level variable that is then imported as necessary. That way it will be available for use from within Flask and by other modules. Here is a simplified version of what I did:

app.py

from flask import Flaskfrom extensions import neo4japp = Flask(__name__)neo4j.init_app(app)

extensions.py

from neo4j_db import Neo4jneo4j = Neo4j()

neo4j_db.py

from neo4j import GraphDatabaseclass Neo4j:    def __init__(self):        self.app = None        self.driver = None    def init_app(self, app):        self.app = app        self.connect()    def connect(self):        self.driver = GraphDatabase.driver('bolt://xxx')        return self.driver    def get_db(self):        if not self.driver:            return self.connect()        return self.driver

example.py

from extensions import neo4jdriver = neo4j.get_db()

And from here driver will contain the database driver that will persist across Flask requests.

Hope that helps anyone that has the same issue.