0

I am starting with sqlalchemy and I am implementing a project with the repository pattern.

In my project I have a class called BaseRepository:

class BaseRepository:

    def __init__(self, model):
        self.session = Session()
        self.model = model

    @db_complete
    def create(self, item):
        self.session.add(item)
        self.session.commit()
        return item

.... others methods.......

I have created a decorator whose function is to initialize the session and close it.

def db_complete(func):
    def wrapper(*args, **kwargs):
        session = args[0].session
        session.begin()
        try:
            response = func(*args, **kwargs)
            return response
        except:
            session.rollback()
            raise
        finally:
            session.close()

    return wrapper

With that code, sometimes it returns the value but sometimes it does not.

And if I update that code to this, calling refresh(), then it work well:

    @db_complete
    def create(self, item):
        self.session.add(item)
        self.session.commit()
        
        # new code
        self.session.refresh(item)

        return item

The question is: Why do I have to refresh?

I am working with mysql+pymysql

Thanks in advance.

  • Can you include how `Session` is originally created? This doesn't seem like the typical flask-sqlalchemy session setup. I don't think you'd usually call `session.close` more than once per web request. If you call close prematurely then everything in the session is going to get thrown out. That is probably why you need `refresh`. – Ian Wilson Mar 26 '22 at 04:08
  • 1
    For example, part 3 of https://flask-sqlalchemy.palletsprojects.com/en/2.x/quickstart/#road-to-enlightenment mentions automatic session closing. – Ian Wilson Mar 26 '22 at 04:10
  • Committing the session will expire the objects it contains - see the linked duplicate. As commented above, if you are using Flask-SQLAlchemy you should understand that it does its own session management, using scoped sessions. – snakecharmerb Mar 26 '22 at 09:43
  • I do not use flask-sqlalchemy. It is my own implementation. – Leandro Hernández Mira Mar 26 '22 at 17:46

0 Answers0