Open3
PythonにおけるリポジトリパターンとUnit Of Work

リポジトリパターンとは

ビジネスロジックの層でトランザクションを担保させる処理をどう実装するか
トランザクションとは
Unit of Workでの解決
Unit of Workとは

Unit of Workでの実際の実装
上記から引用
class DjangoUnitOfWork(AbstractUnitOfWork):
def __enter__(self):
self.batches = repository.DjangoRepository()
transaction.set_autocommit(False) #(1)
return super().__enter__()
def __exit__(self, *args):
super().__exit__(*args)
transaction.set_autocommit(True)
def commit(self):
for batch in self.batches.seen: #(3)
self.batches.update(batch) #(3)
transaction.commit() #(2)
def rollback(self):
transaction.rollback() #(2)
def insert_batch(ref, sku, qty, eta): #(1)
django_models.Batch.objects.create(reference=ref, sku=sku, qty=qty, eta=eta)
def get_allocated_batch_ref(orderid, sku): #(1)
return django_models.Allocation.objects.get(
line__orderid=orderid, line__sku=sku
).batch.reference
@pytest.mark.django_db(transaction=True)
def test_uow_can_retrieve_a_batch_and_allocate_to_it():
insert_batch("batch1", "HIPSTER-WORKBENCH", 100, None)
uow = unit_of_work.DjangoUnitOfWork()
with uow:
batch = uow.batches.get(reference="batch1")
line = model.OrderLine("o1", "HIPSTER-WORKBENCH", 10)
batch.allocate(line)
uow.commit()
batchref = get_allocated_batch_ref("o1", "HIPSTER-WORKBENCH")
assert batchref == "batch1"
@pytest.mark.django_db(transaction=True) #(2)
def test_rolls_back_uncommitted_work_by_default():
...
@pytest.mark.django_db(transaction=True) #(2)
def test_rolls_back_on_error():
...
with
構文をよく使用している例が多い。