由于一个完整的购物商城代码涉及众多方面,包括后端服务、数据库交互、前端展示、用户认证、支付集成等,这里我将为你提供非常简化的示例代码,以展示在不同编程语言中如何开始构建购物商城的核心部分。
1. Python (Flask)
后端 (Flask)
python
from flask import Flask, render_template, request, redirect, url_for
app = Flask(__name__)
# 假设的商品列表(实际中应从数据库获取)
products = [
{'id': 1, 'name': 'Product 1', 'price': 10.00},
{'id': 2, 'name': 'Product 2', 'price': 20.00},
]
# 购物车(这里简化为全局变量,实际中应使用数据库或会话)
cart = []
@app.route('/')
def index():
return render_template('index.html', products=products)
@app.route('/add_to_cart/<int:product_id>', methods=['POST'])
def add_to_cart(product_id):
product = next((item for item in products if item['id'] == product_id), None)
if product:
cart.append(product) # 简化处理,实际应保存到数据库或会话中
return redirect(url_for('cart'))
return 'Product not found', 404
@app.route('/cart')
def cart():
return render_template('cart.html', cart=cart)
if __name__ == '__main__':
app.run(debug=True)
前端 (HTML)
templates/index.html:
html
<!DOCTYPE html>
<html lang="en">
<head>
<!-- ... -->
</head>
<body>
<h1>Welcome to the Shop</h1>
<ul>
{% for product in products %}
<li>
{{ product.name }} - {{ product.price }}
<form action="{{ url_for('add_to_cart', product_id=product.id) }}" method="post">
<button type="submit">Add to Cart</button>
</form>
</li>
{% endfor %}
</ul>
<a href="{{ url_for('cart') }}">View Cart</a>
</body>
</html>