DO NOT COPY OR SHARE - A3Tech / NCTI course material for enrolled students only
A3Tech logo

Introduction to Python Programming · A3Tech

Module 7

Today you will

Build your own shop app: a real web page on top of the Module 6 database.

  1. Run a Streamlit app and explain what the local server does.
  2. Explain the rerun rule: the whole script runs again on every click.
  3. Use widgets to get values, and messages, tables and charts to show results.
  4. Build the shop app step by step on shop_db, with a form that saves new products.

Deep dive A: from print() to a web page

You've watched a Streamlit app at the end of every module. Today you build one. Here's the Module 2 greeting, first as a normal program, then as an app:

hello.py (Module 2 style)
name = input("What's your name? ")
print(f"Welcome to the bakery, {name}!")
hello_app.py
import streamlit as st

st.title("Mama J's Bakery")
name = st.text_input("What's your name?")
if name != "":
    st.write(f"Welcome to the bakery, {name}!")
Output
See the browser: a title, "Mama J's Bakery", and a text box.
Type Jada and press Enter:
Welcome to the bakery, Jada!
Normal programStreamlit app
print()st.write(), st.title(), st.success()...
input()st.text_input(), st.number_input(), st.selectbox()...
Answers appear in Thonny's shellAnswers appear on a web page
Run with the green Run buttonRun with streamlit run hello_app.py in the system shell

Deep dive B: the rerun rule

This is the one big idea of Streamlit. Run this and click the button a few times:

counter.py
import streamlit as st

count = 0
if st.button("Add one"):
    count += 1
st.write("Count:", count)
Output
Click Add one:        Count: 1
Click Add one again:  Count: 1
It never gets to 2.

Every time you click a button, tick a box or change a number, Streamlit runs the whole script again, from the top. So count = 0 runs again every time, and the 1 from last time is wiped.

It's the same thing you saw in Module 6 when a program closes: variables don't remember. That's exactly why the shop app keeps its products and sales in shop.db. The database remembers between reruns.

What you doWhat Streamlit does
Open the appRuns the script top to bottom
Click a buttonRuns the whole script again. That button gives True, just this once
Change a number or tick a boxRuns the whole script again with the new value

Deep dive C: widgets give you values

A widget is anything the user can type in, pick or click. Each one gives back a value you store in a variable, just like input() did.

WidgetGives backLike...
st.text_input("Name")The text typedinput()
st.number_input("How many?")A number, no int() neededint(input())
st.selectbox("Product", a_list)The item picked from the listModule 5 lists
st.checkbox("Loyalty card")True or FalseModule 3 True/False
st.button("Sell")True only on the clickDeep dive B
price_checker.py
import streamlit as st

prices = {"Beef Patty": 5.00, "Cheese Patty": 5.00,
          "Coconut Tart": 4.00, "Sorrel Drink": 3.50}

st.title("Price Checker")
item = st.selectbox("Product", list(prices))
qty = st.number_input("How many?", min_value=1, value=1, step=1)
member = st.checkbox("Loyalty card (10% off)")

total = prices[item] * qty
if member:
    total = total * 0.90
st.metric("Total", f"EC${total:.2f}")
Output
See the browser. Pick Coconut Tart, set How many? to 3:
Total  EC$12.00
Tick Loyalty card (10% off):
Total  EC$10.80

Deep dive D: messages and the Module 3 if

Streamlit has four coloured messages. Pick one with if / elif / else:

  • st.success() green: it worked
  • st.info() blue: just so you know
  • st.warning() yellow: careful
  • st.error() red: something's wrong
stock_check.py
import streamlit as st
import shop_db

shop_db.setup()
st.title("Stock Check")

for p in shop_db.get_products():
    if p["stock"] == 0:
        st.error(f"{p['name']}: SOLD OUT")
    elif p["stock"] < 25:
        st.warning(f"{p['name']}: only {p['stock']} left")
    else:
        st.success(f"{p['name']}: {p['stock']} in stock")
Output
See the browser (fresh shop):
Beef Patty: 40 in stock          (green)
Cheese Patty: 30 in stock        (green)
Coconut Tart: 25 in stock        (green)
Sorrel Drink: only 20 left       (yellow)

Deep dive E: showing the shop's data

Three ways to show data, all straight from shop_db:

CommandShowsGive it
st.dataframe()A table you can scroll and sortA list of dictionaries
st.metric()One big number with a labelA label and a value
st.bar_chart()A bar chartThe data, plus which column goes along (x) and up (y)
sales_view.py
import streamlit as st
import shop_db

shop_db.setup()
st.title("Sales")

st.dataframe(shop_db.get_products())          # a table

report = shop_db.sales_report()
total = 0
for row in report:                            # Module 4 running total
    total += row["money"]
st.metric("Money taken", f"EC${total:.2f}")   # one big number

if report:                                    # only if there are sales
    st.bar_chart(report, x="name", y="money") # a chart
else:
    st.info("No sales yet - make a sale first.")
Output
See the browser, after selling 3 Beef Patty and 2 Coconut Tart:
A table of the 4 products and their stock
Money taken  EC$23.00
A bar chart: Beef Patty 15, Coconut Tart 8

With no sales yet:
Money taken  EC$0.00
No sales yet - make a sale first.   (blue)

Deep dive F: forms - fill in, then save

Normally every change reruns the app straight away. A form groups inputs together so nothing happens until you press its button. Perfect for adding a product: type the name, price and stock, then save once.

add_product_form.py
import streamlit as st
import shop_db

shop_db.setup()
st.title("Add a product")

with st.form("new_product"):
    name = st.text_input("Product name")
    price = st.number_input("Price (EC$)", min_value=0.0, step=0.50)
    stock = st.number_input("Starting stock", min_value=0, step=1)
    saved = st.form_submit_button("Save product")

if saved:
    if name.strip() == "":
        st.warning("Please type a product name.")
    else:
        st.success(shop_db.add_product(name.strip(), price, stock))

st.dataframe(shop_db.get_products())
Output
See the browser. Type Bread Pudding, price 6.00, stock 12, press Save product:
Added Bread Pudding.
The table below now has 5 products.
Press Save product again: Bread Pudding is already in the shop.
Leave the name empty and save: Please type a product name.
with st.form("new_product"): means: everything indented under this line belongs to the form, the same way indented lines belong to an if or a for. st.form_submit_button() is the form's own button, and gives True when it's pressed.

1. Demo: the finished shop app

This is what you're building today. Put it in the same folder as shop_db.py, then run streamlit run shop_app.py. It uses the same shop.db as Module 6, so your Module 6 sales show up here too.

shop_app.py
# shop_app.py - Module 7: Mama J's shop app (the finished version)
# Run it with:  streamlit run shop_app.py     (shop_db.py in the same folder)
import streamlit as st
import shop_db

shop_db.setup()

st.sidebar.title("Mama J's Bakery")
st.sidebar.write("Open Mon-Sat, 7am - 6pm")

st.title("Shop App")

# ---- sell ----
st.header("Make a sale")
names = []
for p in shop_db.get_products():
    names.append(p["name"])
choice = st.selectbox("Product", names)
qty = st.number_input("How many?", min_value=1, value=1, step=1)
if st.button("Sell"):
    message = shop_db.record_sale(choice, qty)
    if "Sold" in message:
        st.success(message)
    else:
        st.error(message)

# ---- add a product ----
st.header("Add a product")
with st.form("new_product"):
    name = st.text_input("Product name")
    price = st.number_input("Price (EC$)", min_value=0.0, step=0.50)
    stock = st.number_input("Starting stock", min_value=0, step=1)
    saved = st.form_submit_button("Save product")
if saved:
    if name.strip() == "":
        st.warning("Please type a product name.")
    else:
        st.success(shop_db.add_product(name.strip(), price, stock))

# ---- stock ----
st.header("Stock")
st.dataframe(shop_db.get_products())
for p in shop_db.query("SELECT name, stock FROM products WHERE stock < 10"):
    st.warning(f"Low stock: {p['name']} ({p['stock']} left)")

# ---- sales ----
st.header("Sales so far")
report = shop_db.sales_report()
if report:
    total = 0
    for row in report:
        total += row["money"]
    st.metric("Money taken", f"EC${total:.2f}")
    st.bar_chart(report, x="name", y="money")
else:
    st.info("No sales yet. Make one above!")
Output
See the browser:
Sidebar: Mama J's Bakery, Open Mon-Sat, 7am - 6pm
Make a sale: pick a product and a number, press Sell
  Sold 2 x Coconut Tart = EC$8.00. 23 left.   (green)
  Try 99 of something: Only 25 Coconut Tart left.   (red)
Add a product: the form from Deep dive F
Stock: the table, plus a yellow warning for anything under 10
Sales so far: Money taken, and a bar chart

2. Build it yourself, step by step

Make a new file, my_shop_app.py. Run it after every step, so you always know which step broke something.

Step 1: title, sidebar and stock. Change the shop name and hours to your own.

my_shop_app.py (step 1)
# Step 1 - title, sidebar and the stock table
import streamlit as st
import shop_db

shop_db.setup()

st.sidebar.title("Mama J's Bakery")
st.sidebar.write("Open Mon-Sat, 7am - 6pm")

st.title("Shop App")

st.header("Stock")
st.dataframe(shop_db.get_products())

Step 2: selling. Add this above st.header("Stock"), so the table updates after a sale.

add to my_shop_app.py (step 2)
st.header("Make a sale")
names = []
for p in shop_db.get_products():
    names.append(p["name"])
choice = st.selectbox("Product", names)
qty = st.number_input("How many?", min_value=1, value=1, step=1)
if st.button("Sell"):
    message = shop_db.record_sale(choice, qty)
    if "Sold" in message:
        st.success(message)
    else:
        st.error(message)

Step 3: the sales report. Add this at the very bottom.

add to my_shop_app.py (step 3)
st.header("Sales so far")
report = shop_db.sales_report()
if report:
    total = 0
    for row in report:
        total += row["money"]
    st.metric("Money taken", f"EC${total:.2f}")
    st.bar_chart(report, x="name", y="money")
else:
    st.info("No sales yet. Make one above!")

Step 4: the form. Copy the form from Deep dive F (from with st.form down) under the selling part.

Bug hunt

This app doesn't crash, but it's losing stock. Open it and change the number a few times without pressing Sell. Watch "Beef Patty left".

04_app_bug.py
# BUG HUNT - this app doesn't crash, but it's losing stock!
# Open it, then change the number box a few times WITHOUT pressing Sell.
# Watch "Beef Patty left". Why does it go down? Fix it so it only sells on Sell.
import streamlit as st
import shop_db

shop_db.setup()
st.title("Quick Sell")

qty = st.number_input("How many Beef Patty?", min_value=1, value=1, step=1)
sell = st.button("Sell")
message = shop_db.record_sale("Beef Patty", qty)
if sell:
    st.success(message)

st.write("Beef Patty left:", shop_db.find_product("Beef Patty")["stock"])
Hints (open only if stuck)
  1. Remember Deep dive B: what runs every time you change the number?
  2. Which line actually sells the patty? Is it inside the if?

Words to know

WordMeaning
StreamlitA Python package that turns a script into a web app
Local serverA small web server on your own computer (http://localhost:8501)
RerunStreamlit runs the whole script again on every click or change
WidgetSomething the user types in, picks or clicks: text box, number box, button
st.formA group of inputs saved with one button
st.metricOne big number with a label
st.sidebarThe panel down the left side of the app

Practice

Homework 7 (5%): one new feature

Add one feature to your shop app. Choose one:

Submit your .py file and a screenshot of it running, before the next module.

MarkMeans
5Runs and has everything
3Runs with parts missing, or has errors
1Started
0Not submitted

Quiz 7

Check yourself here, then take the graded quiz in the quiz section of robotics.a3tech.uk (two tries).

1. Where does a Streamlit app run?
2. What happens when someone clicks a button?
3. Which shows a green message?
4. What does st.form do?
5. Why must record_sale() go inside if st.button("Sell"):?

ADDITIONAL - STREAMLIT APP - SNEAK PEEK 7

Not every app is a shop. Same skills, different idea: a quiz. Next module you build an app about anything you like, and this is the kind of thing you could make.

quiz_app.py
# quiz_app.py - Module 7 sneak peek: a different kind of app, same skills
# Run it with:  streamlit run quiz_app.py

import streamlit as st

st.title("Caribbean Capitals Quiz")

capitals = {                                              # Module 5: a dictionary
    "St. Vincent and the Grenadines": "Kingstown",
    "Barbados": "Bridgetown",
    "Saint Lucia": "Castries",
    "Grenada": "St. George's",
}
choices = ["Bridgetown", "Castries", "Kingstown", "St. George's"]   # Module 5: a list

score = 0                                                 # Module 4: a counter
for country, capital in capitals.items():                 # Module 5: .items()
    answer = st.radio(f"What is the capital of {country}?", choices, index=None, key=country)
    if answer == capital:                                 # Module 3: if
        score += 1

if st.button("Check my score"):
    if score == len(capitals):
        st.success(f"Perfect! {score} out of {len(capitals)}")
        st.balloons()
    elif score >= 2:
        st.info(f"Good try: {score} out of {len(capitals)}")
    else:
        st.warning(f"{score} out of {len(capitals)} - have another go")
Output
See the browser: four questions, each with four choices.
Answer them all correctly and press Check my score:
Perfect! 4 out of 4   (green, with balloons)
Get 2 right:  Good try: 2 out of 4   (blue)
Get 1 right:  1 out of 4 - have another go   (yellow)