Skip to content
Permalink
Browse files
Add files via upload
  • Loading branch information
zhangj123 committed Nov 27, 2021
1 parent 27a478e commit 3f43a590a1ca24ab3aac380b5b2616050b2e4dbd
Show file tree
Hide file tree
Showing 31 changed files with 4,072 additions and 0 deletions.
Binary file not shown.
96 cart.py
@@ -0,0 +1,96 @@
# -*- coding:utf-8 -*-
"""
购物车模块
"""
from flask import Blueprint, render_template, abort, session, redirect, request
from jinja2 import TemplateNotFound
from flask_login import login_required,current_user
from models import Cart,db
shopping_cart = Blueprint("cart", __name__, static_folder="static", template_folder="templates")


@shopping_cart.route("/index")
@login_required
def index():
total = 0
books = Cart.query.filter_by(uid=current_user.id).all() #根据用户id查找购物车数据
for b in books:
total = total + b.quantity * b.book.retail_price #遍历购物车计算总价
return render_template("cart.html", books=books ,total=total )


@shopping_cart.route("/add/<isbn>")
@login_required
def add_2_cart(isbn):
"""
将物品编号是id的物品放入到用户购物车
:param id:
:return:
"""
try:
cart_item = Cart.query.filter_by(uid=current_user.id , book_id=isbn).first()
if cart_item is not None: #先判断该书是否已经加入购物车
cart_item.quantity += 1 #数量加1
else:
item = Cart(uid = current_user.id , book_id = isbn, quantity = 1)#不在购物车就新建一条记录
db.session.add(item)
db.session.commit()
return redirect('/cart/index')
except TemplateNotFound:
abort(404)


@shopping_cart.route("/<isbn>/remove")
@login_required
def remove_from_cart(isbn):
try:
Cart.query.filter_by(uid=current_user.id,book_id=isbn).delete() #根据isbn移除购物车的书
db.session.commit() #提交保存
return redirect("/cart/index")
except Exception as exception:
abort(500)

@shopping_cart.route("/remove_all")
def remove_all():
try:
Cart.query.filter_by(uid=current_user.id).delete() #删除该用户所有购物车数据
db.session.commit()#提交保存
return redirect("/cart/index")
except Exception as exception:
abort(500)

@shopping_cart.route("/pay_check")
@login_required
def pay_check():
try:

res = []
total_money = 0 #图书总价
tota_postage = 3 #邮费
not_enough = [] #库存不足的书
for item in Cart.query.filter_by(uid=current_user.id).all() :
if item.quantity <= item.book.stock:#判断库存是否充足
tota_postage = tota_postage + item.quantity #邮费累加
total_money += item.quantity * item.book.retail_price #图书总价累加
res.append(item)
else:
not_enough.append(item) #库存不足的书
if tota_postage > 4:#根据规则邮费调整
tota_postage = tota_postage - 2
else:
tota_postage = 3
return render_template("check.html",tota_postage=tota_postage,total_money=total_money,res=res,not_enough=not_enough)
except Exception as exception:
print(exception)
abort(500)


@shopping_cart.route("/pay_now")
@login_required
def pay_now():
for item in Cart.query.filter_by(uid=current_user.id).all() : #遍历购物车
if item.quantity <= item.book.stock:#库存充足则扣减对应库存
item.book.stock-=item.quantity
Cart.query.filter_by(uid=current_user.id).delete() #删除所有购物车数据,这里把库存不足的也删了
db.session.commit()
return render_template('payment.html')
@@ -0,0 +1,74 @@
/*
SQLyog v10.2
MySQL - 5.5.5-10.1.21-MariaDB : Database - bookmall
*********************************************************************
*/

/*!40101 SET NAMES utf8 */;

/*!40101 SET SQL_MODE=''*/;

/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
CREATE DATABASE /*!32312 IF NOT EXISTS*/`bookmall` /*!40100 DEFAULT CHARACTER SET utf8 */;

/*Table structure for table `bookinfo` */

CREATE TABLE `bookinfo` (
`isbn` varchar(13) NOT NULL,
`title` varchar(200) NOT NULL,
`author` text NOT NULL,
`img` text NOT NULL,
`stock` int(11) NOT NULL,
`trade_price` int(11) NOT NULL,
`retail_price` int(11) NOT NULL,
`pub_date` date NOT NULL,
`description` text NOT NULL,
PRIMARY KEY (`isbn`),
UNIQUE KEY `isbn` (`isbn`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

/*Data for the table `bookinfo` */

insert into `bookinfo`(`isbn`,`title`,`author`,`img`,`stock`,`trade_price`,`retail_price`,`pub_date`,`description`) values ('2015620065151','网址编辑','dsds','/static/img/5.jpg',77,33,41,'2021-11-04','dsdsdsds'),('2020613225326','books1','sasas','/static/img/1.jpg',10,12,14,'2021-11-03','hello word'),('2020613225327','test2','jak','/static/img/2.jpg',22,22,12,'2021-11-11','21212dscsacscasc sa');

/*Table structure for table `cart` */

CREATE TABLE `cart` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`uid` int(11) DEFAULT NULL,
`book_id` varchar(13) DEFAULT NULL,
`quantity` int(11) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `id` (`id`),
KEY `uid` (`uid`),
KEY `book_id` (`book_id`),
CONSTRAINT `cart_ibfk_1` FOREIGN KEY (`uid`) REFERENCES `user` (`id`),
CONSTRAINT `cart_ibfk_2` FOREIGN KEY (`book_id`) REFERENCES `bookinfo` (`isbn`)
) ENGINE=InnoDB AUTO_INCREMENT=15 DEFAULT CHARSET=utf8;

/*Data for the table `cart` */

insert into `cart`(`id`,`uid`,`book_id`,`quantity`) values (12,1,'2020613225326',2),(14,1,'2020613225327',2);

/*Table structure for table `user` */

CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(20) NOT NULL,
`password` varchar(50) NOT NULL,
`is_admin` tinyint(1) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `username` (`username`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;

/*Data for the table `user` */

insert into `user`(`id`,`username`,`password`,`is_admin`) values (1,'customer1','p455w0rd',0),(2,'customer2','p455w0rd',0),(3,'admin','p455w0rd',1);

/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
81 main.py
@@ -0,0 +1,81 @@
# -*- coding:utf-8 -*-
"""
个性化商城首页
"""
from flask import Flask, render_template, session, redirect, url_for, request
from flask_login import LoginManager, login_required, login_user, current_user, logout_user
from models import *
import pymysql
pymysql.install_as_MySQLdb()
import cart, stock
import os

ROOTDIR = os.path.abspath(os.path.dirname(__file__))

APP = Flask(__name__)
APP.register_blueprint(cart.shopping_cart, url_prefix="/cart")#定义购物车蓝图
APP.register_blueprint(stock.stock, url_prefix="/stock")#库存蓝图
APP.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://debian-sys-maint:M8nVF2jdyGLu0Tx3@localhost:3306/bookmall?charset=utf8'
APP.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
APP.config['SECRET_KEY'] = '@bookstore2021'

db.init_app(APP) #init database
login_manager = LoginManager(APP)
login_manager.login_view = 'login'

@login_manager.user_loader
def load_user(user_id):
return User.query.get(int(user_id))

@APP.route("/login")
def login():
return render_template("login.html")


@APP.route("/logout")#用户注销
def logout():
logout_user()
return redirect("/login")


@APP.route("/do_login", methods=["POST"])#用户登录
def do_login():
user_name = request.form.get('user_name')#获取表单提交的用户名
password = request.form.get('password')#密码
# 拿着获取到的用户名和密码进行登录
user = User.query.filter_by( username = user_name,password=password ).first() #查找该用户是否存在
if user:
login_user(user)
if user.is_admin == True:#判断是否为管理员,跳转不同地址
return redirect('/stock')
else:
return redirect('/home')
else:
return render_template("login.html",err="Incorrect password!")#错误提示
return redirect("/")


@APP.route("/")
@APP.route("/home")
@login_required
def index():
costs = 0
num = 0
books = Bookinfo.query.filter(Bookinfo.stock > 0 )#查找库存大于0的书
cart = Cart.query.filter_by(uid=current_user.id).count() #判断购物车是否为空
if cart > 0:
for i in Cart.query.filter_by(uid=current_user.id ).all():#遍历购物车
num+=i.quantity #总数目
costs += i.book.retail_price*i.quantity #计算总价
return render_template("index.html", my_books=books,num=num,costs=costs )


@APP.route("/detail/<isbn>")
@login_required
def detail(isbn):#图书详情
book = Bookinfo.query.get( isbn )#根据ISBN查找
return render_template("detail.html", book=book )


if __name__ == "__main__":
APP.run(host='0.0.0.0', port=5000, debug=False)
@@ -0,0 +1,38 @@
from flask_sqlalchemy import SQLAlchemy
from flask_login import UserMixin
db = SQLAlchemy() #实例化数据库对象

class Bookinfo(db.Model):#图书信息表
__tablename__ = 'bookinfo'

isbn = db.Column(db.String(13), unique=True, primary_key = True )
title = db.Column(db.String(200), nullable=False)
author= db.Column(db.Text, nullable=False)
img =db.Column(db.Text, nullable=False)
stock = db.Column(db.Integer, nullable=False)
trade_price =db.Column(db.Integer, nullable=False)
retail_price =db.Column(db.Integer, nullable=False)
pub_date= db.Column(db.Date, nullable=False)
description =db.Column(db.Text, nullable=False)

class User(UserMixin, db.Model):#用户表
__tablename__ = 'user'

id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(20), unique=True, nullable=False)
password = db.Column(db.String(50), nullable=False)
is_admin = db.Column(db.Boolean, nullable=False )


class Cart(db.Model):#购物车表
__tablename__ = 'cart'

id = db.Column(db.Integer, unique=True, primary_key=True )
uid = db.Column(db.Integer, db.ForeignKey('user.id'))
book_id = db.Column(db.String(13), db.ForeignKey('bookinfo.isbn') )
quantity = db.Column(db.Integer, nullable=False )
book = db.relationship('Bookinfo', backref='cart')




0 comments on commit 3f43a59

Please sign in to comment.