10
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Flask + SQLAlchemy でよさそうなトランザクション管理

Posted at

よくあるやつ

Transactions using Flask-SQLAlchemy にあるように

from contextlib import contextmanager
@contextmanager
def transaction():
    try:
        yield
        db.session.commit()
    except Exception:
        db.session.rollback()
        raise

を作成して、それを

def hogehoge():
  with transaction():
    ...

と処理を書く。

記述ところが少しなら良いけど、色んなところにあると、少しめんどくさい。

よさそうなやつ

from functools import wraps


def transactional(func):
    @wraps(func)
    def decorator(*args, **kwargs):
        if db.session.info["in_transaction"]:
            return func(*args, **kwargs)
        else:
            db.session.info["in_transaction"] = True
            try:
                result = func(*args, **kwargs)
                db.session.commit()
                return result
            except Exception as e:
                db.session.rollback()
                raise e
            finally:
                db.session.info["in_transaction"] = False

    return decorator

@transactionalアノテーションを用意して、それをトランザクション管理したいところに付与する。

@transactional
def hogehoge():
  ...

基本的に、トランザクション管理する時ってfunction単位でやると思うので、
個人的にはこっちの方が良いなって思う。

10
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?