Database Reference
In-Depth Information
In order to support returning inventory from timed-out carts, we'll need to create an index on
the status and last_modified properties. Since our query on last_modified is an inequal-
ity, we should place it last in the compound index:
>>> db . cart . ensure_index ([( 'status' , 1 ), ( 'last_modified' , 1 )])
Error handling
The previous operations do not account for one possible failure situation. If an exception oc-
curs after updating the shopping cart but before updating the inventory collection, then we
have an inconsistent situation where there is inventory “trapped” in a shopping cart.
To account for this case, we'll need a periodic cleanup operation that finds inventory items
that have carted items and check to ensure that they exist in some user's active cart, and re-
turn them to available inventory if they do not. Our approach here is to visit each product
with some carted entry older than a specified timestamp. Then, for each SKU found:
1. Load the cart that's possibly expired. If it's actually "active" , refresh the carted
entry in the product .
2. If an "active" cart was not found to match the carted entry, then the carted is re-
moved and the available inventory is updated:
def
def cleanup_inventory ( timeout ):
now = datetime . utcnow ()
threshold = now - timedelta ( seconds = timeout )
# Find all the expiring carted items
for
for item iin db . product . find (
{ 'carted.timestamp' : { '$lt' : threshold }}):
# Find all the carted items that matched
carted = dict (
( carted_item [ 'cart_id' ], carted_item )
for
for carted_item iin item [ 'carted' ]
iif carted_item [ 'timestamp' ] < threshold )
# First Pass: Find any carts that are active and refresh the carted
# items
for
for cart iin db . cart . find (
{ '_id' : { '$in' : carted . keys () },
'status' : 'active' }):
 
Search WWH ::




Custom Search