Start learning free

LESSON 66 OF 66 · NOSQL: CHOOSING A DATABASE

Which One Fits? in Python

Practice

No store is best at everything. In this lesson you write a small version of three shop features, each in the store that fits it: a cart in Redis, an order in MongoDB and a money transfer in SQL.

A cart that vanishes. A Redis hash is one key with a field per product, like a small dict. hset has no time limit, so call r.expire(key, seconds) afterwards to give the key a time to live. When the time runs out, Redis deletes the key by itself. r.ttl(key) gives the seconds left: -1 means no expiry, and -2 means there is no key at all.

r.hset("session:bo", mapping={"page": "home", "theme": "dark"})
r.expire("session:bo", 600)

An order in one piece. In SQL an order is a row in orders plus rows in order_items, and you read it back with a JOIN. In MongoDB the items list sits inside the order document: one insert_one writes it, and one find_one reads it back.

Money, all or nothing. shop.db has an accounts table: ana has 50, shop has 0, and a CHECK keeps every balance at 0 or more. A transfer is two UPDATEs. Inside a with db: block they form a transaction. Both are saved when the block ends, and if a line inside it raises an error, both are undone.

Your script must print the lines below. The check then moves the clock 31 minutes ahead, and the cart must be gone. Then it tries to move 500 from ana, who has 20 left: the CHECK fails, and both balances must stay as they were.

Cart: {'Mug': '2', 'Pen': '5'} expires in 1800
Order: {'customer_id': 1, 'status': 'paid', 'items': [{'product': 'Lamp', 'quantity': 1, 'unit_price': 29}, {'product': 'Mug', 'quantity': 2, 'unit_price': 12}]}
Move 30 from ana to shop
Accounts: [('ana', 20), ('shop', 30)]
Best fit: Redis for the cart (expires), MongoDB for the order (one document), SQL for money (all or nothing)

Your task: store Ana's cart as a hash and make it expire after 1800 seconds, and insert order 8 into mongo.orders as one document. Then fill transfer with a transaction of two UPDATEs, and print which store fits each feature and why.


Assignment
Follow the Coding Tutorial to write the cart, the order and the transfer, each in the store that fits it.


Hint
Both UPDATEs go inside with db:, the target's first. When the source's UPDATE breaks the CHECK, the block undoes the target's change too.


STEP 1 OF 7
    Ctrl + Enter to check

    Nosql Pick in Python

    Keep going with Python1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free