[Django]-Best way to integrate SqlAlchemy into a Django project

27👍

for the first two, engine and Session, you can put them in settings.py; they are, configuration, after all.

Actually creating a session requires slightly more care, since a session is essentially a ‘transaction’. The simplest thing to do is to create it in each view function when needed, and commit them just before returning. If you’d like a little bit more magic than that, or if you want/need to use the session outside of the view function, you should instead define some middleware, something like

class MySQLAlchemySessionMiddleware(object):
    def process_request(self, request):
        request.db_session = settings.Session()

    def process_response(self, request, response):
        try:
            session = request.db_session
        except AttributeError:
            return response
        try:
            session.commit()
            return response
        except:
            session.rollback()
            raise

    def process_exception(self, request, exception):
        try:
            session = request.db_session
        except AttributeError:
            return
        session.rollback()

Then, every view will have a db_session attribute in their requests, which they can use as they see fit, and anything that was added will get commited when the response is finished.

Don’t forget to add the middleware to MIDDLEWARE_CLASSES

Leave a comment