用Python编写一个简单的电子商务网站
发布时间:2023-12-04 09:21:30
电子商务网站是一个允许用户在线购买商品和服务的网站。Python是一种流行的编程语言,具有强大的功能和易于学习的语法。下面是一个简单的电子商务网站的Python示例代码:
from flask import Flask, render_template, request, redirect
# 创建Flask应用程序
app = Flask(__name__)
app.config['SECRET_KEY'] = 'your-secret-key'
# 存储商品信息的列表
products = [
{'id': 1, 'name': '手机', 'price': 999},
{'id': 2, 'name': '电视', 'price': 1999},
{'id': 3, 'name': '笔记本电脑', 'price': 3999}
]
@app.route('/')
def index():
return render_template('index.html', products=products)
@app.route('/product/<int:id>')
def product(id):
product = None
for p in products:
if p['id'] == id:
product = p
break
return render_template('product.html', product=product)
@app.route('/cart', methods=['GET', 'POST'])
def cart():
if request.method == 'POST':
product_id = int(request.form.get('product_id', 0))
product_quantity = int(request.form.get('product_quantity', 0))
for p in products:
if p['id'] == product_id:
p['quantity'] = product_quantity
break
return redirect('/cart')
total_price = 0
for p in products:
total_price += p['price'] * p.get('quantity', 0)
return render_template('cart.html', products=products, total_price=total_price)
if __name__ == '__main__':
app.run(debug=True)
上述示例使用了Flask框架创建一个简单的电子商务网站。在代码中,我们定义了3个商品,并使用列表存储它们的信息。在index()函数中,我们渲染了主页模板,并将商品列表传递给模板。
在product()函数中,我们根据传入的商品ID查找对应的商品,并渲染产品详情页面模板。
在cart()函数中,如果请求方法是POST,我们更新商品的数量,并重定向到购物车页面。如果请求方法是GET,我们计算购物车中所有商品的总价格,并渲染购物车页面模板。
在main()函数中,我们启动应用程序并打开调试模式。
要运行这个简单的电子商务网站,你需要安装Flask库,并在终端上执行以下命令:
$ pip install flask $ python ecommerce_website.py
然后,在浏览器中访问http://localhost:5000/即可查看网站。
这个示例是一个简单的电子商务网站,你可以根据自己的需求进行扩展和修改。例如,可以添加用户认证功能、购物车结算功能、支付功能等。与此同时,你可以使用数据库来存储商品信息,以实现更灵活的管理和查询。
