Skip to content
Permalink
3a41c5ac11
Switch branches/tags

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Go to file
 
 
Cannot retrieve contributors at this time
64 lines (53 sloc) 2.36 KB
# 定义用户表和收藏商品表
class User(Base):
__tablename__ = 'users'
user_id = Column(Integer, primary_key=True, autoincrement=True)
username = Column(String, nullable=False, unique=True)
password = Column(String, nullable=False)
favorites = relationship("UserFavorite", back_populates="user")
browsing_history = relationship("UserBrowsingHistory", back_populates="user")
class UserFavorite(Base):
__tablename__ = 'user_favorites'
favorite_id = Column(Integer, primary_key=True, autoincrement=True)
user_id = Column(Integer, ForeignKey('users.user_id'), nullable=False)
product_id = Column(Integer, nullable=False)
user = relationship("User", back_populates="favorites")
class UserBrowsingHistory(Base):
__tablename__ = 'user_browsing_history'
history_id = Column(Integer, primary_key=True, autoincrement=True)
user_id = Column(Integer, ForeignKey('users.user_id'), nullable=False)
product_id = Column(Integer, nullable=False)
browse_time = Column(DateTime, default=datetime.utcnow)
user = relationship("User", back_populates="browsing_history")
# 在用户数据库中创建表
Base.metadata.create_all(engine_user)
# 添加用户
def add_user(username, password):
new_user = User(username=username, password=password)
session_user.add(new_user)
session_user.commit()
# 添加用户收藏的商品
def add_favorite(user_id, product_id):
new_favorite = UserFavorite(user_id=user_id, product_id=product_id)
session_user.add(new_favorite)
session_user.commit()
#在week8 database2 中有创建商品的部分
# 添加新商品
def add_product(name, image, description, category, store):
new_product = Product(product_name=name, product_image=image, product_description=description, category=category, store=store)
session_product.add(new_product)
session_product.commit()
# 更新商品信息
def update_product(product_id, name=None, image=None, description=None, category=None, store=None):
product = session_product.query(Product).filter(Product.product_id == product_id).one()
if name:
product.product_name = name
if image:
product.product_image = image
if description:
product.product_description = description
if category:
product.category = category
if store:
product.store = store
session_product.commit()