Start learning free

LESSON 121 OF 188 · BACKEND: SPEED

Measure First in Python

Practice

Before you make the shop faster, measure it: otherwise you can't tell whether a change really helped. In this module you measure the work a request does by counting its database queries. A count gives the same answer on every computer, while a time in milliseconds changes with the machine and with whatever else it is doing.

Every route in the shop asks the database through one helper, run_query, so that is the one place to count: a wrapper that does its job and keeps score on the way. The score lives in a dictionary, because a function can change a value inside a dictionary without any extra keyword. Here is the same idea on another value, a counter of visits:

visits = {"count": 0}

@app.get("/hello")
def hello():
    visits["count"] += 1
    return jsonify({"message": "Hi!", "visits": visits["count"]})

To read the count, add a debug route: a tool for you, the developer, not a page for customers. The count only goes up, so read it before and after a request: the difference is what that request cost. Your code must give these answers, in this order:

GET /debug/queries  →  200  {"queries": 0}
GET /products/1  →  200  {"category": "kitchen", "id": 1, "name": "Mug", "price": 12, "stock": 10}
GET /debug/queries  →  200  {"queries": 1}
GET /customers/1/orders  →  200  [{"id": 1, "items": […], …}, {"id": 3, "items": […], …}]
GET /debug/queries  →  200  {"queries": 4}
GET /customers/5/orders  →  200  []
GET /debug/queries  →  200  {"queries": 5}

Customer 1's orders cost 3 queries: one for the orders, then one for the items of each of the 2 orders. Customer 5 has no orders, so only the first query runs. Reading the count is not a query, so it never counts itself.

Your task: add a dictionary stats whose key "queries" starts at 0, make run_query add 1 to it every time it runs, and add a route for GET /debug/queries whose function show_queries answers stats as JSON.


Assignment
Follow the Coding Tutorial to count every query in run_query and show the count at GET /debug/queries.


Hint
The counting line goes first in run_query, the helper every route uses. += 1 adds one to the value already in the dictionary.


STEP 1 OF 5
    Ctrl + Enter to check

    Speed Count Queries 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