基于flask写的一个小商城mall项目

  • Post author:
  • Post category:其他


1.项目实现功能

项目主要是分为用户、管理员两个角色,分别对两个角色的功能进行展示

2.项目技术

项目主要是后端开发,利用flask框架进行开发、数据库采用mysql;其中运用蓝图blueprint、装饰器进行权限控制等

3.项目实现

(1)整体项目结构

(2)先列一下整体都需要的

① utils:

import hashlib
import time
import simplejson as json


def result(code=200, d={},message=''):
    data = dict()  # object.__dict__
    data['code'] = code
    data['data'] = d
    data['message']=message
    return json.dumps(data, ensure_ascii=False)


def md5(m):
    return hashlib.md5(m.encode()).hexdigest()


def getNowDataTime():
    return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())


def getTimeStamp():
    return time.time()


def getOrderNum():
    orderNum = str(getTimeStamp()).replace('.', '')
    return orderNum

②连接数据库的配置信息

# true表示返回的json文件中中文字符用ascii码表示
JSON_AS_ASCII = False
# 数据库的配置变量
class MySQLConfig(object):
    HOSTNAME = '127.0.0.1'
    PORT = '3306'
    DATABASE = 'mall'
    USERNAME = 'root'
    PASSWORD = ''
    DB_URI = 'mysql+pymysql://{}:{}@{}:{}/{}'.format(USERNAME, PASSWORD, HOSTNAME, PORT, DATABASE)
    SQLALCHEMY_DATABASE_URI = DB_URI
    # 关闭数据库修改跟踪操作[提高性能],可以设置为True,这样可以跟踪操作:
    SQLALCHEMY_TRACK_MODIFICATIONS = False

    # 开启输出底层执行的sql语句
    SQLALCHEMY_ECHO = True

    # session
    SECRET_KEY = "123"

③全局变量

from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()

④数据库表

from exts import db


class User(db.Model):
    __tablename__ = "user"
    __table_args__ = {'mysql_collate': 'utf8_general_ci'}

    _id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(30))
    username = db.Column(db.String(11), unique=True)
    password = db.Column(db.String(64))
    avatar = db.Column(db.String(256))
    age = db.Column(db.Integer)
    idCard = db.Column(db.String(18))
    gneder = db.Column(db.String(2))
    createTime = db.Column(db.DateTime)
    loginTime = db.Column(db.DateTime)
    logoutTime = db.Column(db.DateTime)
    balance = db.Column(db.Float(10), default=0)
    vip = db.Column(db.Integer, db.ForeignKey("vip._id"))

    def __repr__(self):
        return "User:%s" % self.name


goodsCourt = db.Table("goodsCourt",
                      db.Column("goods_id", db.Integer, db.ForeignKey("goods._id")),
                      db.Column("court_id", db.Integer, db.ForeignKey("court._id"))
                      )


class Court(db.Model):
    __tablename__ = "court"
    __table_args__ = {'mysql_collate': 'utf8_general_ci'}
    _id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer, db.ForeignKey('user._id'))
    number = db.Column(db.Integer, default=0)  # 记录商品种类
    goods = db.relationship("Goods", secondary=goodsCourt, backref=db.backref("court", lazy="dynamic"), lazy="dynamic")


class Address(db.Model):
    __tablename__ = "address"
    __table_args__ = {'mysql_collate': 'utf8_general_ci'}
    _id = db.Column(db.Integer, primary_key=True)
    province = db.Column(db.String(18))
    town = db.Column(db.String(18))
    county = db.Column(db.String(18))
    detail = db.Column(db.String(200))
    user_id = db.Column(db.Integer, db.ForeignKey("user._id"))

    def __repr__(self):
        return "Address:%s" % self.detail


class Vip(db.Model):
    __tablename__ = "vip"
    __table_args__ = {'mysql_collate': 'utf8_general_ci'}
    _id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(50))
    level = db.Column(db.Integer, default=0)

    def __repr__(self):
        return "Vip:%s" % self.name


class Ad(db.Model):
    __tablename__ = "ad"
    __table_args__ = {'mysql_collate': 'utf8_general_ci'}
    _id = db.Column(db.Integer, primary_key=True)
    content = db.Column(db.String(50))
    createTime = db.Column(db.DateTime)
    displayTime = db.Column(db.DateTime)
    endTime = db.Column(db.DateTime)
    image = db.Column(db.String(256))
    video = db.Column(db.String(256))
    title = db.Column(db.String(100))
    intro = db.Column(db.String(500))

    def __repr__(self):
        return "Ad:%s" % self.content


class Admin(db.Model):
    __tablename__ = "admin"
    __table_args__ = {'mysql_collate': 'utf8_general_ci'}
    _id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(30))
    account = db.Column(db.String(11))
    password = db.Column(db.String(64))
    createTime = db.Column(db.DateTime)
    loginTime = db.Column(db.DateTime)
    logoutTime = db.Column(db.DateTime)
    level = db.Column(db.Integer, default=0)

    def __repr__(self):
        return "Admin:%s" % self.name


class GoodsType(db.Model):
    __tablename__ = "goodsType"
    __table_args__ = {'mysql_collate': 'utf8_general_ci'}
    _id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(50))
    number = db.Column(db.Integer, default=0)

    def __repr__(self):
        return "GoodsType:%s" % self.name


class Goods(db.Model):
    __tablename__ = "goods"
    __table_args__ = {'mysql_collate': 'utf8_general_ci'}
    _id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(100))
    goodsType_id = db.Column(db.Integer, db.ForeignKey("goodsType._id"))
    originPrice = db.Column(db.Float(10))
    sellPrice = db.Column(db.Float(10))
    contains = db.Column(db.Integer, default=0)
    produceTime = db.Column(db.DateTime)
    expireTime = db.Column(db.DateTime)
    createTime = db.Column(db.DateTime)
    image = db.Column(db.String(256))
    createAddress_id = db.Column(db.Integer, db.ForeignKey("address._id"))
    sendAddress_id = db.Column(db.Integer, db.ForeignKey("address._id"))
    intro = db.Column(db.String(500))
    lookTimes = db.Column(db.Integer, default=0)
    buyTimes = db.Column(db.Integer, default=0)
    likeTimes = db.Column(db.Integer, default=0)

    def __repr__(self):
        return "Goods:%s" % self.name


class VipReceipt(db.Model):
    __tablename__ = "vip_receipt"
    __table_args__ = {'mysql_collate': 'utf8_general_ci'}
    _id = db.Column(db.Integer, primary_key=True)
    orderNum = db.Column(db.String(30))
    createTime = db.Column(db.DateTime)
    payValue = db.Column(db.Float(10))
    cutoffValue = db.Column(db.Float(10))
    user_id = db.Column(db.Integer, db.ForeignKey("user._id"))
    vipId = db.Column(db.Integer)

    def __repr__(self):
        return "VipReceipt:%s" % self.orderNum


class ReceiptItem(db.Model):
    __tablename__ = "receipt_item"
    __table_args__ = {'mysql_collate': 'utf8_general_ci'}
    _id = db.Column(db.Integer, primary_key=True)
    goodsId = db.Column(db.Integer)
    number = db.Column(db.Integer, default=0)


class Receipt(db.Model):
    __tablename__ = "receipt"
    __table_args__ = {'mysql_collate': 'utf8_general_ci'}
    _id = db.Column(db.Integer, primary_key=True)
    orderNum = db.Column(db.String(30))
    createTime = db.Column(db.DateTime)
    payValue = db.Column(db.Float(10))
    cutoffValue = db.Column(db.Float(10))
    user_id = db.Column(db.Integer, db.ForeignKey("user._id"))
    itemId = db.Column(db.String(100), default="[]")

    def get_goods_id_list(self):
        idStrList = self.itemId[1:-1].split(',')
        idList = []
        for item in idStrList:
            idList.append(int(item))
        return idList

    def __repr__(self):
        return "Receipt:%s" % self.orderNum


class Comment(db.Model):
    __tablename__ = "comment"
    __table_args__ = {'mysql_collate': 'utf8_general_ci'}
    _id = db.Column(db.Integer, primary_key=True)
    createTime = db.Column(db.DateTime)
    content = db.Column(db.String(500))
    points = db.Column(db.Integer, default=5)
    screenCut = db.Column(db.String(256))
    user = db.Column(db.Integer, db.ForeignKey("user._id"))
    good = db.Column(db.Integer, db.ForeignKey("goods._id"))

    def __repr__(self):
        return "Comment:%s" % self.content

(3)登录登出

from datetime import datetime

from flask import Flask, request, jsonify, session
from flask_migrate import Migrate

from blueprints.admin import bp as admin_bp
from blueprints.user import bp as user_bp
from blueprints.mall import bp as mall_bp
from blueprints.visitor import bp as visitor_bp
import config
from config import *
from exts import db
from blueprints.forms import LoginForm
from models import Admin, User

app = Flask(__name__)

# 组装蓝图 将book、course、user模块都组装在main.py中
app.register_blueprint(admin_bp)
app.register_blueprint(user_bp)
app.register_blueprint(mall_bp)
app.register_blueprint(visitor_bp)
# 配置项
app.config.from_object(MySQLConfig)

db.init_app(app)
db.app = app

# migrate = Migrate(app, db)


# db.create_all()


@app.route("/login", methods=['POST', 'GET'])
def login():
    """三个都有登录功能 所以直接在app.py中进行登录功能"""
    if request.method == 'GET':
        return "login.html"
    else:
        form = LoginForm(request.form)
        if form.validate():
            account = form.account.data
            password_input = form.password.data
            type = form.type.data
            if type == 'admin':
                admin_model = Admin.query.filter_by(account=account).first()
                print("admin:", admin_model)
                if admin_model:
                    if password_input == admin_model.password:
                        session["_id"] = admin_model._id
                        admin_model.loginTime = datetime.now()
                        db.session.commit()
                        print("登录成功")
                        return jsonify({"code": 200, "message": " admin suceess"})
                    else:
                        print("密码错误")
                        return jsonify({"code": 403, "message": "admin 密码错误"})
                else:
                    print("不存在该admin")
                    return jsonify({"code": 404, "message": "admin 不存在"})
            else:
                user_model = User.query.filter_by(username=account).first()
                if user_model:
                    if password_input == user_model.password:
                        session["_id"] = user_model._id
                        user_model.loginTime = datetime.now()
                        db.session.commit()
                        print("登录成功")
                        return jsonify({"code": 200, "message": "user suceess"})
                    else:
                        print("密码错误")
                        return jsonify({"code": 403, "message": "user 密码错误"})
                else:
                    print("不存在该user")
                    return jsonify({"code": 404, "message": "user 不存在"})
        else:
            print("请输入正确格式的账号或密码")
            return jsonify({"code": 500, "message": "格式错误"})


# 退出系统
@app.route("/logout", methods=["POST"])
def logout():
    if request.method == "POST":
        _id = session["_id"]
        _type = request.form["type"]
        if _type == "admin":
            admin = Admin.query.get(_id)
            admin.logoutTime = datetime.now()
        else:
            user = User.query.get(_id)
            user.logoutTime = datetime.now()
        del session["_id"]
        return jsonify({"code": 200, "message": "退出登录成功"})


@app.route('/')
def hello_world():
    return 'Hello World!'


if __name__ == '__main__':
    app.run(debug=True)



版权声明:本文为m0_57098080原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。