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.