当前位置:网站首页>Based on the flask mall administrator functions
Based on the flask mall administrator functions
2022-08-02 13:20:00 【pony with slow hair】
1.功能分析
管理员:
Mainly is to manage commodity information and user information
1.登录退出
2.商品相关:
Additions, deletions and modifications to the commodity table
添加商品
删除商品
修改商品信息
Statistics background information
Also present in the add-on item:
添加商品类别、添加管理地址
3.用户相关
Adds, deletes, modifies and checks the user table
修改用户信息
添加用户
查看用户
4.广告相关
添加广告
删除广告
View ad
5.用户VIP的管理:
查看VIP
删除VIP
查看VIP订单
6.Super administrator management of administrators:
Additions to administrators
删除管理员
7.查看所有订单
8.Popular product recommendation:
根据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.Use the management of the product:增删改查
3.Use the management of advertising
4.对用户VIP的管理
4.对管理员的管理:
Only super administrators can add or delete administrators"""
@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": "Return list successfully"})
else:
return jsonify({"code": 404, "message": "Return list identification"})
@bp.route("/addUser", methods=['POST', 'GET'])
@login_required
def addUser():
"""Added in adminuser与注册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": "Please enter valid update information"})
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": "Return list successfully"})
else:
return jsonify({"code": 404, "message": "Failed to return list"})
@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": "Please enter valid update information"})
else:
return jsonify({"code": 404, "message": "The item to be updated does not exist"})
@bp.route("/deleteGoods/int<goodId>", methods=['POST'])
@login_required
def deleteGoods(goodId):
Goods.query.filter_by(_id=goodId).delete()
return jsonify({"code": 200, "message": "删除商品成功"})
# The addition of product categories
@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)
# Product category query
@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)
# Deletion of product categories
@bp.route("/deleteGoodsType/int<typeId>", methods=['POST'])
@login_required
def deleteGoodsType(typeId):
GoodsType.query.filter_by(_id=typeId).delete()
return result(200, meaasge="The product category was deleted successfully")
# 地址添加
@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="Address added successfully")
# 地址查询
@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="添加广告成功")
# Get all ads
@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, "Get ad success")
# Ads removed
@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, "Ad deletion succeeded")
# 用户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用户成功')
# 查看所有人VIPOrder order status
@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)
# View the order status of everyone's product orders
@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)
# 对管理员的管理:只有超级管理员rootIt is possible to delete and add administrators
@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="Add administrator successfully")
@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="Deletion of administrator succeeded")
# Get user comments
@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="The user comment was obtained successfully")
# Popular product recommendation 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)
# Add more items to the cart 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)
边栏推荐
猜你喜欢
Scala基础语法入门(三)Scala中的各种运算符
【C语言】细品分支结构——switch语句
FreeRTOS--stack experiment
SQL Server 2019 installation error 0 x80004005 service there is no timely response to the start or control request a detailed solution
LeetCode_139_word split
RISC-V 指令格式和6种基本整数指令
86.(cesium之家)cesium叠加面接收阴影效果(gltf模型)
In-depth analysis and use of Ribbon load balancing
【C语言】明解数组(1)
【C语言】函数哪些事儿,你真的get到了吗?(1)
随机推荐
sql concat() function
js数组递归使用
我的创作纪念日
Four seasons of trees realized by svg
什么是 commonjs2
第48篇-timestamp2参数分析【2022-08-01】
3 ways for OpenFeign to set headers
How to implement waterfall flow layout (what is waterfall flow layout)
永远退出机器学习界!
.Net 5.0 Quick Start Redis
MFC入门教程(深入浅出MFC)
自媒体创作怎样提高原创度,打造爆款作品?
Redis all
How to use the database like tap water?|Tencent Cloud Database TDSQL-C
图论之Kruskal,最小生成树如何优雅解题?
Introduction to Graph Neural Networks (GNN) "Recommended Collection"
photo-sphere-viewer Chinese documentation
How to improve the originality of self-media creation and create popular works?
Redis全部
svg balloon rises explosion js special effect