Commits

Jean-Tiare Le Bigot committed 42b7644

transaction doc

  • Participants
  • Parent commits 602c95d

Comments (0)

Files changed (2)

docs/api/transaction.rst

 need to be implemented. Optionally, you may overload the whole schema or set
 ``transient=True``. A ``_setup()`` method may also be implemented.
 
+During the transaction itself, please set ``requester_id`` field to any relevant
+interger unless the transaction is ``transient``. ``_setup()`` is a good place
+to do it.
+
+Note: ``transient`` flag may be toggled on a per instance basis. It may even be
+toggled in one of the transactors.
+
+Use case: Bundle purchase
+-------------------------
+
+::
+
+    from dynamodb_mapper.transactions import Transaction, TargetNotFoundError
+
+    # define PlayerExperience, PlayerPowerUp, PlayerSkins, Players with user_id as hash_key
+
+    class InsufficientResourceError(Exception):
+        pass
+
+    bundle = {
+        "cost": 150,
+        "items": [
+            PlayerExperience,
+            PlayerPowerUp,
+            PlayerSkins
+        ]
+    }
+
+    class BundleTransaction(Transaction):
+        transient = False # Make it explicit. This is anyway the default.
+        __table__ = "mygame-dev-bundletransactions"
+
+        def __init__(self, user_id, bundle):
+            self.requester_id = user_id
+            self.bundle = bundle
+
+        # _setup() is not needed here
+
+        def _get_transactors(self):
+            transactors = [(
+                lambda: Players.get(self.requester_id),
+                lambda player: self.user_payment(player)
+            )]
+
+            for Item in self.bundle.items:
+                transactors.append((
+                    lambda: Item.get(self.requester_id),
+                    lambda item: item.do_stuff()
+                ))
+
+            return transactors
+
+        def user_payment(self, player):
+            if player.balance < self.bundle.cost:
+                raise InsufficientResourceError()
+            player.balance -= self.bundle.cost
+
+    # Run the transaction
+    try:
+        transaction = BundleTransaction(42, bundle)
+        transaction.commit()
+    except InsufficientResourceError:
+        print "Ooops, user {} has not enough coins to proceed...".format(42)
+
+    #That's it !
+
+This example has been kept simple on purpose. In a real world application, you
+certainly would *not* model your data this way ! You can notice the power of this
+approach that is compatible with ``lambda`` niceties.
 
 Related exceptions
 ==================

dynamodb_mapper/transactions.py

     collecting rewards for a player, you may wish to keep track of related
     transactions by user_id hence set requester_id to user_id
 
-    Deriving class **MUST** set field ``__table__``
+    Deriving class **MUST** set field ``__table__`` and ``requester_id`` field
     """
 
     __hash_key__ = "requester_id"