streamlit
Streamlit 是一个基于 Python 的 Web 应用程序框架,致力于以更高效、更灵活的方式可视化数据,并分析结果。
Streamlit是一个开源库,可以帮助数据科学家和学者在短时间内开发机器学习 (ML) 可视化仪表板。只需几行代码,我们就可以构建并部署强大的数据应用程序。
功能设计
- 商品展示
- 商品选购
- 加入购物车
- 购物车结算
- 增加新商品
- 文件保存商品信息
函数/Page 设计
函数名 | 说明 |
---|---|
load_products() | 打开或创建存储商品信息的文件,并读取信息 |
save_products(products) | 将商品信息保存在文件中 |
show_products() | 用按钮显示所有商品信息 |
Select Product | 读取商品名和数量,传给购物车 |
Shopping Cart | 展示所有已选购商品,计算总价 |
Checkout | 计算总价,点击买单后清空购物车 |
Add New Product | 读取新商品信息,加入商品信息列表,写入文件,重新加载文件 |
源码
import streamlit as st
import json
import os
def load_products():
if not os.path.exists('products.json'):
with open('products.json', 'w') as file:
file.write('{}') # 创建一个空的 JSON 文件
with open('products.json', 'r') as file:
products = json.load(file)
return products
def save_products(products):
with open('products.json', 'w') as file:
json.dump(products, file, indent=4)
# 初始化购物车
if 'shopping_cart' not in st.session_state:
st.session_state.shopping_cart = []
# 初始化商品信息
if 'products' not in st.session_state:
st.session_state.products = load_products()
def show_products():
st.write("Current Products:")
products = st.session_state.products
product_names = list(products.keys())
num_products = len(product_names)
# 创建五列
col1, col2, col3, col4, col5 = st.columns(5)
# 在每列中显示产品信息
for i in range(num_products):
if i % 5 == 0:
if col1.button(f"{product_names[i]} - ${products[product_names[i]]['price']} - {products[product_names[i]]['description']}"):
st.session_state.shopping_cart.append((product_names[i], 1))
elif i % 5 == 1:
if col2.button(f"{product_names[i]} - ${products[product_names[i]]['price']} - {products[product_names[i]]['description']}"):
st.session_state.shopping_cart.append((product_names[i], 1))
elif i % 5 == 2:
if col3.button(f"{product_names[i]} - ${products[product_names[i]]['price']} - {products[product_names[i]]['description']}"):
st.session_state.shopping_cart.append((product_names[i], 1))
elif i % 5 == 3:
if col4.button(f"{product_names[i]} - ${products[product_names[i]]['price']} - {products[product_names[i]]['description']}"):
st.session_state.shopping_cart.append((product_names[i], 1))
else:
if col5.button(f"{product_names[i]} - ${products[product_names[i]]['price']} - {products[product_names[i]]['description']}"):
st.session_state.shopping_cart.append((product_names[i], 1))
def main():
st.title('Welcome to the Convenience Store')
page = st.sidebar.radio("Page", ["Select Product", "Shopping Cart", "Checkout", "Add New Product"])
if page == "Select Product":
show_products()
selected_product = st.selectbox('Select a product', list(st.session_state.products.keys()), format_func=lambda x: f"{x} - ${st.session_state.products[x]['price']} - {st.session_state.products[x]['description']}")
quantity = st.number_input('Quantity', min_value=1, max_value=10)
if st.button('Add to cart'):
st.session_state.shopping_cart.append((selected_product, quantity))
st.success('Added to cart!')
st.experimental_rerun() # 刷新页面,更新商品信息
elif page == "Shopping Cart":
st.title('Shopping Cart')
for item in st.session_state.shopping_cart:
st.write(f"{item[0]} - Quantity: {item[1]}")
total_cost = sum([st.session_state.products[item[0]]['price'] * item[1] for item in st.session_state.shopping_cart])
st.write(f"Total Cost: ${total_cost}")
elif page == "Checkout":
st.title('Checkout')
total_cost = sum([st.session_state.products[item[0]]['price'] * item[1] for item in st.session_state.shopping_cart])
st.write(f"Total Cost: ${total_cost}")
if st.button('Confirm Purchase'):
st.success('Thank you for your purchase!')
st.session_state.shopping_cart = []
elif page == "Add New Product":
st.title('Add New Product')
new_product_name = st.text_input('Product name')
new_product_price = st.number_input('Product price')
new_product_description = st.text_input('Product description')
if st.button('Add Product'):
st.session_state.products[new_product_name] = {'price': new_product_price, 'description': new_product_description}
save_products(st.session_state.products) # 将新的商品信息保存到文件
st.success('Product added successfully!')
st.experimental_rerun() # 刷新页面,显示新商品
if __name__ == "__main__":
main()
运行示例
总结
streamlit使用非常方便简单,可以快速创建各种web应用。