使用Python和CGI创建基于数据库的在线商城系统
发布时间:2023-12-19 02:54:59
在Python和CGI(Common Gateway Interface)的帮助下,我们可以创建一个基于数据库的在线商城系统。下面是一个简单的例子,其中包含了创建和连接到数据库、添加商品到数据库、展示商品列表和购物车功能。
首先,我们需要安装和配置数据库(例如MySQL)。这里我们使用PyMySQL库来连接MySQL数据库。
import pymysql
# 连接到数据库
def connectDB():
conn = pymysql.connect(host='localhost', port=3306, user='root', password='root', db='online_shop')
cursor = conn.cursor()
return conn, cursor
# 关闭数据库连接
def closeDB(conn, cursor):
cursor.close()
conn.close()
# 创建商品表
def createProductTable(cursor):
cursor.execute("CREATE TABLE IF NOT EXISTS products (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255), price DECIMAL(10,2))")
# 添加商品到数据库
def addProduct(name, price, cursor):
cursor.execute("INSERT INTO products (name, price) VALUES (%s, %s)", (name, price))
# 获取商品列表
def getProducts(cursor):
cursor.execute("SELECT * FROM products")
return cursor.fetchall()
# 渲染商品列表
def renderProducts(products):
output = ""
for product in products:
output += f"<li>{product[0]}: {product[1]} - ${product[2]}</li>"
return output
# CGI处理函数
def main():
conn, cursor = connectDB()
createProductTable(cursor)
# 添加商品到数据库
addProduct("Product 1", 9.99, cursor)
addProduct("Product 2", 19.99, cursor)
addProduct("Product 3", 29.99, cursor)
# 获取商品列表
products = getProducts(cursor)
# 输出HTML页面
print("Content-type:text/html\r
\r
")
print("<html>")
print("<head><title>Online Shop</title></head>")
print("<body>")
print("<h1>Welcome to our Online Shop</h1>")
print("<h2>Products:</h2>")
print("<ul>")
print(renderProducts(products))
print("</ul>")
print("</body>")
print("</html>")
closeDB(conn, cursor)
# 执行CGI处理函数
if __name__ == '__main__':
main()
在这个例子中,我们创建了一个名为products的数据库表来存储商品信息。addProduct()函数用于向数据库中添加商品,getProducts()函数用于从数据库中获取商品列表。
在main()函数中,我们连接到数据库,创建商品表,添加一些商品到数据库,并从数据库中获取商品列表。然后,我们使用HTML格式渲染商品列表,并将其输出到浏览器。
使用Python和CGI可以实现一个简单的基于数据库的在线商城系统。当然,这只是一个起点,你可以根据需要扩展和改进该系统,例如实现用户登录、购物车功能等。
