当前位置:网站首页>基于flask商城的管理员功能
基于flask商城的管理员功能
2022-08-02 13:02:00 【头发慢点掉的小马】
1.功能分析
管理员:
主要就是管理商品信息和用户信息
1.登录退出
2.商品相关:
对商品表的增删改查
添加商品
删除商品
修改商品信息
统计后台信息
在添加商品中还存在:
添加商品类别、添加管理地址
3.用户相关
对用户表的增删改查
修改用户信息
添加用户
查看用户
4.广告相关
添加广告
删除广告
查看广告
5.用户VIP的管理:
查看VIP
删除VIP
查看VIP订单
6.超级管理员对管理员的管理:
对管理员的增加
删除管理员
7.查看所有订单
8.热销商品推荐:
根据likeTime进行推荐
buyTimes进行推荐
2.实现代码
import json
from datetime import datetime
from flask import Blueprint, jsonify, request
from blueprints.forms import RegisterForm, UpdateUserForm, AddGoodsForm
from decorators import login_required
from exts import db
from models import User, Goods, GoodsType, Address, Ad, Vip, Admin, VipReceipt, Receipt, Comment
from utils import getNowDataTime, result, getOrderNum
bp = Blueprint("admin", __name__, url_prefix="/admin")
"""管理员功能:
1.对用户的管理:增删改查
2.用商品的管理:增删改查
3.用广告的管理
4.对用户VIP的管理
4.对管理员的管理:
只有超级管理员可以进行添加删除管理员"""
@bp.route("/userList", methods=['POST'])
@login_required
def UserList():
userList = User.query.filter().all() # 返回user列表
for user in userList:
print(user.username)
print(json.dumps(userList))
if userList:
return jsonify({"code": 200, "list": json.dumps(userList), "message": "返回列表成功"})
else:
return jsonify({"code": 404, "message": "返回列表识别"})
@bp.route("/addUser", methods=['POST', 'GET'])
@login_required
def addUser():
"""在管理员中添加user与注册user的逻辑一致"""
if request.method == 'GET':
return "addUser.html"
else:
form = RegisterForm(addUser.form)
if form.validate():
print("验证成功")
username = form.username.data
password = form.password.data
print(username, password)
# 密码加密
# hash_password = generate_password_hash(password=password)
create_time = datetime.now()
# 1.通过username查询user表 如果存在就通知已存在该用户 不存在就新建
user_model = User.query.filter_by(username=username).first()
if user_model:
print("该用户名已被注册,请重新输入")
return jsonify({"code": 401, "message": "该用户名已被注册,请重新输入"})
user = User(username=username, password=password, createTime=create_time)
db.session.add(user)
db.session.commit()
return jsonify({"code": 200, "message": "user 添加成功"})
else:
print("user验证失败")
return jsonify({"code": 401, "message": "user验证失败"})
@bp.route("/updateUser/<int:user_id>", methods=['POST'])
@login_required
def updateUser(user_id):
"""更新用户信息:
1.通过前端传过来的用户id查询用户
2.若用户存在:
更新信息
3.用户不存在:
返回“不存在该用户”"""
user_update = User.query.filter_by(_id=user_id).first()
if user_update:
form = UpdateUserForm(request.form)
if form.validate:
username = form.username.data
gneder = form.gneder.data
user_update.username = username
user_update.gneder = gneder
db.session.commit()
return jsonify({"code": 200, "message": "user 更新成功"})
else:
jsonify({"code": 401, "message": "请输入合法的更新信息"})
else:
return jsonify({"code": 404, "message": "待更新用户不存在"})
@bp.route("/deleteUser/<int:user_id>", methods=['POST'])
@login_required
def deleteUser(user_id):
User.query.filter_by(_id=user_id).delete()
return jsonify({"code": 200, "message": "删除用户成功"})
@bp.route("/GoodsList")
@login_required
def GoodsList():
goodsList = Goods.query.filter().all() # 返回good列表
for good in goodsList:
print(good.name)
if good:
return jsonify({"code": 200, "message": "返回列表成功"})
else:
return jsonify({"code": 404, "message": "返回列表失败"})
@bp.route("/addGoods", methods=['POST'])
@login_required
def addGoods():
if request.method == "POST":
form = request.form
image = request.files["image"]
save_path = "./static/goods/" + getOrderNum() + image.filename
image.save(save_path)
data = {
"name": form["name"],
"goodsType_id": form["goodsType"],
"originPrice": form["originPrice"],
"sellPrice": form["sellPrice"],
"contains": form["contains"],
"produceTime": form["produceTime"],
"expireTime": form["expireTime"],
"createTime": getNowDataTime(),
"image": save_path,
"createAddress_id": form["createAddress"],
"sendAddress_id": form["sendAddress"],
"intro": form["intro"]
}
goods = Goods(**data)
db.session.add(goods)
db.session.commit()
return result(200)
@bp.route("/updateGoods/<int:goodId>", methods=['POST'])
@login_required
def updateGoods(goodId):
good_update = Goods.query.filter_by(_id=goodId).first()
if good_update:
form = AddGoodsForm(request.form)
if form.validate:
name = form.username.data
good_update.username = name
db.session.commit()
return jsonify({"code": 200, "message": "good 更新成功"})
else:
jsonify({"code": 401, "message": "请输入合法的更新信息"})
else:
return jsonify({"code": 404, "message": "待更新商品不存在"})
@bp.route("/deleteGoods/int<goodId>", methods=['POST'])
@login_required
def deleteGoods(goodId):
Goods.query.filter_by(_id=goodId).delete()
return jsonify({"code": 200, "message": "删除商品成功"})
# 商品分类的添加
@bp.route("/goods/type/add", methods=['POST'])
@login_required
def goods_type_add():
if request.method == 'POST':
name = request.form["name"]
_type = GoodsType(name=name)
db.session.add(_type)
db.session.commit()
return result(200)
# 商品分类的查询
@bp.route("/goods/type/list", methods=['GET'])
@login_required
def goods_type():
if request.method == 'GET':
typeList = GoodsType.query.all()
data = dict()
data['data'] = []
for type in typeList:
dic = type.__dict__
del dic["_sa_instance_state"]
data["data"].append(dic)
print(type.name)
return result(200, data)
# 商品分类的删除
@bp.route("/deleteGoodsType/int<typeId>", methods=['POST'])
@login_required
def deleteGoodsType(typeId):
GoodsType.query.filter_by(_id=typeId).delete()
return result(200, meaasge="删除商品分类成功")
# 地址添加
@bp.route("/address/add", methods=['POST'])
@login_required
def address_add():
if request.method == 'POST':
form = request.form
data = {
"province": form["province"],
"town": form["town"],
"county": form["county"],
"detail": form["detail"],
}
address = Address(**data)
db.session.add(address)
db.session.commit()
return result(200, message="地址添加成功")
# 地址查询
@bp.route("/address/list", methods=['GET'])
@login_required
def addressList():
if request.method == 'GET':
addressList = Address.query.all()
data = dict()
data['data'] = []
for address in addressList:
dic = address.__dict__
del dic["_sa_instance_state"]
data["data"].append(dic)
return result(200, data, "获取地址列表成功")
# 广告
@bp.route("/ads/add", methods=["POST"])
@login_required
def ads_add():
if request.method == "POST":
form = request.form
image = request.files["image"]
save_path = "./static/ads/" + image.filename
image.save(save_path)
data = {
"content": form["content"],
"createTime": getNowDataTime(),
"displayTime": form["displayTime"],
"endTime": form["endTime"],
"image": save_path,
"title": form["title"],
"intro": form["intro"],
}
ad = Ad(**data)
db.session.add(ad)
db.session.commit()
return result(200, message="添加广告成功")
# 获取所有广告
@bp.route("/ads/list")
@login_required
def ads():
if request.method == "GET":
# ads = Ad.query.filter_by(displayTime = getNowDataTime())
ads = Ad.query.filter_by().all()
data = dict()
data["data"] = []
for ad in ads:
dic = ad.__dict__
del dic["_sa_instance_state"]
data["data"].append(dic)
return result(200, data, "获取广告成功")
# 广告删除
@bp.route("/ads/delete/<int:adId>", methods=["DELETE"])
@login_required
def ads_delete(adId):
if request.method == "DELETE":
Ad.query.filter_by(_id=adId).delete()
return result(200, "删除广告成功")
# 用户VIP添加
@bp.route("/vip/add", methods=['POST'])
@login_required
def vip_add():
if request.method == 'POST':
name = request.form['name']
level = request.form['level']
vip = Vip(name=name, level=level)
db.session.add(vip)
db.session.commit()
return result(200, message='VIP添加成功')
# 获取VIP信息
@bp.route("/vip/list", methods=['GET'])
@login_required
def vip_list():
vip_list = Vip.query.filter_by().all()
data = dict()
data['data'] = []
for vip in vip_list:
dic = vip.__dict__
del dic["_sa_instance_state"]
data["data"].append(dic)
return result(200, data, "获取vip用户成功")
# vip用户的删除
@bp.route("/vip/delete/<int:vipId>", methods=['DELETE'])
@login_required
def vip_delete(vipId):
Vip.query.filter_by(_id=vipId).delete()
return result(200, message='删除vip用户成功')
# 查看所有人VIP订单订单情况
@bp.route("/vipreceipt/<int:start>/<int:nums>", methods=["POST", "GET"])
@login_required
def admin_vipreceipt(start, nums):
if request.method == "GET":
nums = VipReceipt.query.all().count()
return result(200, {"nums": nums})
if request.method == "POST":
receipts = VipReceipt.query.offset(start).limit(nums)
data = dict()
data["data"] = []
for receipt in receipts:
dic = receipt.__dict__
del dic["_sa_instance_state"]
data["data"].append(dic)
return result(200, data)
# 查看所有人商品订单订单情况
@bp.route("/receipt/<int:start>/<int:nums>", methods=["POST", "GET"])
@login_required
def admin_receipt(start, nums):
if request.method == "GET":
nums = Receipt.query.all().count()
return result(200, {"nums": nums})
if request.method == "POST":
receipts = Receipt.query.offset(start).limit(nums)
data = dict()
data["data"] = []
for receipt in receipts:
goodsIdList = receipt.get_goods_id_list()
dic = receipt.__dict__
del dic["_sa_instance_state"]
dic["goodsList"] = []
for goodsId in goodsIdList:
goods = Goods.query.with_entities(Goods.name, Goods.originPrice, Goods.sellPrice).filter_by(_id=goodsId)
d = goods.__dict__
del d["_sa_instance_state"]
dic["goodsList"].append(d)
data["data"].append(dic)
return result(200, data)
# 对管理员的管理:只有超级管理员root可以进行管理员的删除和添加
@bp.route("/admin/add/<int:adminId>", methods=['POST'])
@login_required
def admin_add(adminId):
admin = Admin.query.filter_by(_id=adminId).first()
if admin.account == 'root':
form = request.form
data = {
"account": form['account'],
"password": form['password'],
"createTime": getNowDataTime()
}
admin = Admin(**data)
db.session.add(admin)
db.session.commit()
return result(200, message="添加管理员成功")
@bp.route("/admin/delete/<int:adminId>/<int:adminDeId>")
@login_required
def admin_delete(adminId, adminDeId):
admin = Admin.query.filter_by(_id=adminId).first()
if admin.account == 'root':
Admin.query.filter_by(_id=adminDeId).delete()
return result(200, message="删除管理员成功")
# 获取用户的评论
@bp.route("/getComment/<int:userId>/<int:goodId>")
@login_required
def getComment(userId, goodId):
commentList = Comment.query.filter_by(user=userId, good=goodId).all()
data = dict()
data['data'] = []
for comment in commentList:
dic = comment.__dict__
del dic["_sa_instance_state"]
data['data'].append(dic)
return result(200, data, message="获取该用户评论成功")
# 热销的商品推荐 buyTimes 推荐
@bp.route("/recommend/buytimes")
@login_required
def goods_recommend_buytime():
if request.method == "GET":
goods = Goods.query.order_by(db.desc(Goods.buyTimes)).limit(50)
data = dict()
data["data"] = []
for good in goods:
data["data"].append({
"id": good._id,
"name": good.name,
"originPrice": good.originPrice,
"sellPrice": good.sellPrice,
"image": good.image,
"lookTimes": good.lookTimes,
"likeTimes": good.likeTimes,
"buyTimes": good.buyTimes,
})
return result(200, data)
# 添加购物车多的商品 likeTimes 推荐
@bp.route("/recommend/liketimes")
@login_required
def goods_recommend_liketimes():
if request.method == "GET":
goods = Goods.query.order_by(db.desc(Goods.likeTimes)).limit(50)
data = dict()
data["data"] = []
for good in goods:
data["data"].append({
"id": good._id,
"name": good.name,
"originPrice": good.originPrice,
"sellPrice": good.sellPrice,
"image": good.image,
"lookTimes": good.lookTimes,
"likeTimes": good.likeTimes,
"buyTimes": good.buyTimes,
})
return result(200, data)
边栏推荐
- FreeRTOS--Priority Experiment
- 节省50%成本!京东云重磅发布新一代混合CDN产品
- Intouch Historian历史曲线配置导入导出
- 瀑布流式布局怎么实现(什么是瀑布流布局)
- Set proxy server (Google+IE) "Recommended Collection"
- FreeRTOS--栈实验
- 你知道图论的spfa吗?
- PHP+MYSQL [Student Information Management System] (Minimalist Edition)
- 80篇国产数据库实操文档汇总(含TiDB、达梦、openGauss等)
- 图论之Kruskal,最小生成树如何优雅解题?
猜你喜欢
RESTful style (detailed introduction + case implementation)
UAC绕过学习-总结
单例模式的七种写法,你都知道吗?
js true 3d histogram plugin
FreeRTOS creation tasks - dynamic creation, static creation
你知道图论的spfa吗?
Ribbon负载均衡的深度分析和使用
js semi-circle loading progress animation js special effects
linux basic command explanation
第48篇-timestamp2参数分析【2022-08-01】
随机推荐
节省50%成本!京东云重磅发布新一代混合CDN产品
Closures in JS
Redis全部
80篇国产数据库实操文档汇总(含TiDB、达梦、openGauss等)
js true 3d histogram plugin
svg气球升起爆炸js特效
FreeRTOS creation tasks - dynamic creation, static creation
openGauss数据库基本操作(超详细)
新特性解读 | MySQL 8.0 GIPK 不可见主键
WPF效果第一百九十三篇之登录实现
Good shooting js game source code
js cool dashboard plugin
Article 48 - Analysis of timestamp2 parameters【2022-08-01】
php——三篇夯实根基第一篇
国产 GPU 创业潮 喧嚣下的资本游戏
FreeRTOS--栈实验
FreeRTOS创建任务--动态创建、静态创建
.Net 5.0快速上手 Redis
RestTemplate use: set request header, request body
qt 编译报错 No rule to make target