[PYTHON] How to handle session in SQLAlchemy

Introduction

In SQLAlchemy, after creating a session, it is necessary to perform commit (), rollback (), and close () as needed. Here, we will create a class that performs DB operations and summarize how to pass sessions. In the following, it is assumed that the following model class exists.

models.py


class User(Base):
    __tablename__="user" #Specify table name
    id=Column(Integer, primary_key=True)
    first_name=Column(String(255))
    last_name=Column(String(255))

Bad treatment of session

It is not good to make it like the following source code.

wrong_way.py


from models import User

class FirstName(object):
    def update_first_name(self, user_id, first_name):
        session=Session()
        try:
            user=session.query(User).filter(User.id==user_id).one() #id=user_Extract obj which is id
            user.first_name=first_name #first_Change name
            session.commit()
        except:
            session.rollback()
            raise


class LastName(object):
    def update_last_name(self, user_id, last_name):
        session=Session()
        try:
            user=session.query(User).filter(User.id==user_id).one() #id=user_Extract obj which is id
            user.first_name=first_name #last_Change name
            session.commit()
        except:
            session.rollback()
            raise


def run_my_program():
    FirstName().update_first_name(1, "update_first_name")
    LastName().update_last_name(1, "update_last_name")

Because the same session is not used in ʻupdate_first_name and ʻupdate_last_name in run_my_program. "First_name was updated, but last_name was not." This is because something like this happens.

Good way to handle session 1

Therefore, it can be solved by using the following source code.

right_way_1.py


from models import User

class FirstName(object):
    def update_first_name(self, user_id, first_name, session):
        user=session.query(User).filter(User.id==user_id).one()
        user.first_name=first_name


class LastName(object):
    def update_last_name(self, user_id, last_name, session):
        user=session.query(User).filter(User.id==user_id).one()
        user.first_name=first_name


def run_my_program():
    session = Session()
    try:
        FirstName().update_first_name(session)
        LastName().update_last_name(session)
        session.commit()
    except:
        session.rollback()
        raise
    finally:
        session.close()

By doing this, the same session will be used for ʻupdate_first_name and ʻupdate_last_name. "Only one ran successfully" The situation like this does not occur.

Good way to handle session 2

Next, we will introduce how to handle session using context manager. As for the context manager, the following articles are very easy to understand and helpful, so the explanation is omitted here. What is a Python context manager? The story I searched for

right_way_2.py


from models import User

from contextlib import contextmanager

@contextmanager
def session_scope():
    session = Session()  # def __enter__
    try:
        yield session  #Pass session with as
        session.commit()  #If nothing happens, commit()
    except:
        session.rollback()  #Rollback if error occurs()
        raise
    finally:
        session.close()  #Either way, it will eventually close()


class FirstName(object):
    def update_first_name(self, user_id, first_name, session):
        user=session.query(User).filter(User.id==user_id).one()
        user.first_name=first_name


class LastName(object):
    def update_last_name(self, user_id, last_name, session):
        user=session.query(User).filter(User.id==user_id).one()
        user.first_name=first_name


def run_my_program():
    with session_scope() as session:
        FirstName().update_first_name(session)
        LastName().update_last_name(session)

References

This article was written with reference to the following information. -Official Documents (Session Basics) · [What is a Python context manager? The story I investigated (https://blog.mtb-production.info/entry/2018/04/10/183000)

Recommended Posts

How to handle session in SQLAlchemy
How to handle Japanese in Python
How to handle consecutive values in MySQL
How to handle datetime type in python sqlite3
How to update with SQLAlchemy?
How to Alter with SQLAlchemy?
How to develop in Python
How to handle data frames
How to Delete with SQLAlchemy?
How to perform learning in SageMaker without session timeout
How to handle JSON in Ruby, Python, JavaScript, PHP
[Python] How to do PCA in Python
How to use classes in Theano
How to write soberly in pandas
How to collect images in Python
How to update Spyder in Anaconda
How to use SQLite in Python
How to convert 0.5 to 1056964608 in one shot
How to reflect CSS in Django
How to kill processes in bulk
How to use Mysql in python
How to wrap C in Python
How to use ChemSpider in Python
How to use PubChem in Python
[Blender] How to handle mouse and keyboard events in Blender scripts
How to run TensorFlow 1.0 code in 2.0
How to INNER JOIN with SQLAlchemy
How to log in to Docker + NGINX
How to search by string to use mysql json_contains in SQLAlchemy
How to call PyTorch in Julia
How to handle multiple versions of CUDA in the same environment
<Pandas> How to handle time series data in a pivot table
How to use calculated columns in CASTable
[Introduction to Python] How to use class in Python?
How to suppress display error in matplotlib
How to access environment variables in Python
How to get parent id with sqlalchemy
How to dynamically define variables in Python
How to do R chartr () in Python
How to convert csv to tsv in CLI
How to delete expired sessions in Django
[Itertools.permutations] How to put permutations in Python
How to use Google Test in C
How to implement nested serializer in drf-flex-fields
How to work with BigQuery in Python
How to execute commands in jupyter notebook
How to do'git fetch --tags' in GitPython
How to get a stacktrace in python
How to display multiplication table in python
How to extract polygon area in Python
How to reassign index in pandas dataframe
How to check opencv version in python
How to enable SSL (TLS) in Apache
How to use Anaconda interpreter in PyCharm
How to specify non-check target in Flake8
How to switch python versions in cloud9
How to adjust image contrast in Python
How to use __slots__ in Python class
How to dynamically zero pad in Python
How to do Server-Sent Events in Django
How to use regular expressions in Python