Ejemplo n.º 1
0
    def uploadByFile(file): # 定义上传文件函数。参数是文件类
        config_upload = app.config['UPLOAD']
        resp = {'code': 200, 'msg': '操作成功', 'data': {}}
        filename = secure_filename(file.filename) # 获得上传的文件名
        ext = filename.rsplit(".", 1)[1]  # 获得类型(扩展名)。即文件名以.切割,拿到后面部分。
        if ext not in config_upload['ext']:
            resp['code'] = -1
            resp['msg'] = "不允许的扩展类型文件"
            return resp

        root_path = app.root_path + config_upload['prefix_path']  # 图片存放路径。app.root_path获取全局路径
        file_dir = getCurrentData("%Y%m%d")  # 按照日期生成文件夹
        save_dir = root_path + file_dir  # 最终的保存地址
        if not os.path.exists( save_dir ):
            os.mkdir(save_dir)
            os.chmod(save_dir, stat.S_IRWXU | stat.S_IRGRP | stat.S_IRWXO )  # 给这个文件赋予权限。拥有者最高权限|。权限参考:http://www.runoob.com/python/os-chmod.html

        file_name = str(uuid.uuid4()).replace("-", "") + "." + ext  # 重命名文件名
        file.save("{0}/{1}".format(save_dir, file_name))  # 保存文件。在save_dir路径下

        # 存储图片路径到数据库
        model_image = Image()
        model_image.file_key = file_dir + "/" + file_name
        model_image.created_time = getCurrentData()
        db.session.add(model_image)
        db.session.commit()

        resp['data'] = {
            'file_key': file_dir + "/" + file_name
        }
        return resp
Ejemplo n.º 2
0
def login():
    resp = {'code': 200, 'msg': '操作成功', 'data': {}}  # 定义全局变量,操作成功返回信息
    req = request.values
    code = req['code'] if 'code' in req else ''
    if not code or len(code) < 1:
        resp['code'] = -1
        resp['msg'] = "需要code"
        return jsonify(resp)

    ## 通过code 可以获得用户的一些基本信息。获得的方法分到了公共方法里面
    openid = MemberService.getWeChatOpenId(code)
    if openid is None:  # 如果用户的请求里面拿到的code没有 openid(用户唯一标识)
        resp['code'] = -1
        resp['msg'] = "调用微信出错"
        return jsonify(resp)

    nickname = req['nickName'] if 'nickName' in req else ''
    sex = req['gender'] if 'gender' in req else 0  # 性别
    avatar = req['avatarUrl'] if 'avatarUrl' in req else ''  # 头像链接

    ## 建立数据库,确认这个openid是不是唯一的
    """
    判断是否已经注册过了,注册了直接返回一些信息
    """
    bind_info = OauthMemberBind.query.filter_by(
        openid=openid, type=1).first()  # type=1:信息来源表示是微信用户

    if not bind_info:  # 没有信息,即没注册。进行注册
        model_member = Member()
        model_member.nickname = nickname
        model_member.sex = sex
        model_member.avatar = avatar
        model_member.salt = MemberService.geneSalt()  # 秘钥
        model_member.created_time = getCurrentData()
        model_member.updated_time = getCurrentData()
        db.session.add(model_member)
        db.session.commit()

        # 建立绑定关系
        model_bind = OauthMemberBind()
        model_bind.member_id = model_member.id
        model_bind.type = 1  # 信息来源1,
        model_bind.openid = openid
        model_bind.extra = ''
        model_bind.created_time = getCurrentData()
        model_bind.updated_time = getCurrentData()
        db.session.add(model_bind)
        db.session.commit()

        bind_info = model_bind  # 将新的变量赋值给 bind_info,

    member_info = Member.query.filter_by(
        id=bind_info.member_id).first()  # 如果注册过了。会员信息 = 会员id (上面绑定用户的id)

    token = "%s#%s" % (MemberService.geneAuthCode(member_info), member_info.id
                       )  # 将token(加密字符串),返回给前台处理
    resp['data'] = {'token': token}  # 返回给前台的数据
    return jsonify(resp)
Ejemplo n.º 3
0
def set():
    default_pwd = "******"
    if request.method == "GET":
        resp_data = {}
        req = request.args
        uid = int(req.get("id", 0))
        user_info = None
        if uid:
            user_info = User.query.filter_by(uid=uid).first()
        resp_data['user_info'] = user_info
        return ops_render("account/set.html", resp_data)
    elif request.method == "POST":

        resp = {'code': 200, 'msg': '操作成功', 'data': {}}
        req = request.values
        id = req['id'] if 'id' in req else 0
        nickname = req['nickname'] if 'nickname' in req else None
        mobile = req['mobile'] if 'mobile' in req else None
        email = req['email'] if 'email' in req else None
        login_name = req['login_name'] if 'login_name' in req else None
        login_pwd = req['login_pwd'] if 'login_pwd' in req else None

        if not all([nickname, mobile, email, login_name, login_pwd]):
            resp['code'] = -1
            resp['msg'] = '参数不完整'
            return jsonify(resp)

        has_in = User.query.filter(User.login_name == login_name,
                                   User.uid != id).first()
        if has_in:
            resp['code'] = -1
            resp['msg'] = '该登录名已存在,请换一个'
            return jsonify(resp)

        user_info = User.query.filter_by(uid=id).first()
        if user_info:
            model_user = user_info
        else:
            model_user = User()
            model_user.created_time = getCurrentData()
            model_user.login_salt = UserService.geneSalt()

        model_user.nickname = nickname
        model_user.mobile = mobile
        model_user.email = email
        model_user.login_name = login_name
        if default_pwd != login_pwd:
            model_user.login_pwd = UserService.genePwd(login_pwd,
                                                       model_user.login_salt)
        model_user.updated_time = getCurrentData()

        db.session.add(model_user)
        db.session.commit()
        return jsonify(resp)
Ejemplo n.º 4
0
def login():
    resp = {'code': 200, 'msg': 'OK', 'data': {}}
    req = request.json
    app.logger.info(req)
    code = req['code'] if 'code' in req else ''
    # code:0238KQlC0DJFil2QrWnC06y1mC08KQl4
    if not code or len(code) < 1:
        resp['code'] = -1
        resp['msg'] = '需要code'
        return jsonify(resp)

    openid = MemberService.getWeChatOpenId(code)
    if openid is None:
        resp['code'] = -1
        resp['msg'] = '调用微信出错'
        return jsonify(resp)

    # openid:oesTl5ZSMGOOY6lvlZijsxmPtowU
    nickname = req['nickName'] if 'nickName' in req else ''
    sex = req['gender'] if 'gender' in req else ''
    avatar = req['avatarUrl'] if 'avatarUrl' in req else ''
    '''
        判断是否已经注册过,注册了直接返回一些信息
    '''
    bind_info = OauthMemberBind.query.filter_by(openid=openid, type=1).first()
    if not bind_info:
        model_member = Member()
        model_member.nickname = nickname
        model_member.sex = sex
        model_member.avatar = avatar
        model_member.salt = MemberService.geneSalt()
        model_member.updated_time = model_member.created_time = getCurrentData(
        )
        db.session.add(model_member)
        db.session.commit()

        model_bind = OauthMemberBind()
        model_bind.member_id = model_member.id
        model_bind.type = 1
        model_bind.openid = openid
        model_bind.extra = ''
        model_bind.updated_time = model_bind.created_time = getCurrentData()
        db.session.add(model_bind)
        db.session.commit()

        bind_info = model_bind

    member_info = Member.query.filter_by(id=bind_info.member_id).first()
    token = "%s#%s" % (MemberService.geneAuthCode(member_info), member_info.id)
    resp['data'] = {'token': token}
    return jsonify(resp)
Ejemplo n.º 5
0
def login():
    resp = {'code': 200, 'msg': '成功', 'data': {}}
    req = request.values

    code = req['code'] if 'code' in req else ''
    if not code or len(code) < 1:
        resp['code'] = -1
        resp['msg'] = '需要code'
        return jsonify(resp)
    openid = MemberService.getWeChatOpenId(code)
    if openid is None:
        resp['code'] = -1
        resp['msg'] = '调用微信出错'
        print("1111111111111111111")
        return jsonify(resp)

    nickname = req['nickName'] if 'nickName' in req else ''
    sex = req['gender'] if 'gender' in req else 0
    avatar = req['avatarUrl'] if 'avatarUrl' in req else ''
    '''
        判断是否已经注册了
    '''
    bind_info = OauthMemberBind.query.filter_by(openid=openid, type=1).first()
    if not bind_info:
        model_member = Member()
        model_member.nickname = nickname
        model_member.sex = sex
        model_member.avatar = avatar
        model_member.salt = MemberService.geneSalt()
        model_member.updated_time = model_member.created_time = getCurrentData(
        )
        db.session.add(model_member)
        db.session.commit()
        model_bind = OauthMemberBind()
        model_bind.member_id = model_member.id
        model_bind.type = 1
        model_bind.openid = openid
        model_bind.extra = ''
        model_bind.updated_time = model_bind.created_time = getCurrentData()
        db.session.add(model_bind)
        db.session.commit()

        bind_info = model_bind

    member_info = Member.query.filter_by(id=bind_info.member_id).first()
    token = '%s#%s' % (MemberService.geneAuthCode(member_info), member_info.id)
    resp['data'] = {'token': token}

    return jsonify(resp)
Ejemplo n.º 6
0
    def uploadByFile(file):
        config_upload = app.config['UPLOAD']
        resp = {'code': 200, 'msg': '操作成功~~', 'data': {}}
        filename = secure_filename(file.filename)
        ext = filename.rsplit(".", 1)[1]
        if ext not in config_upload['ext']:
            resp['code'] = -1
            resp['msg'] = "不允许的扩展类型文件"
            return resp

        root_path = app.root_path + config_upload['prefix_path']
        # 不使用getCurrentDate创建目录,为了保证其他写的可以用,这里改掉,服务器上好像对时间不兼容
        file_dir = datetime.datetime.now().strftime("%Y%m%d")
        save_dir = root_path + file_dir
        if not os.path.exists(save_dir):
            os.mkdir(save_dir)
            os.chmod(save_dir, stat.S_IRWXU | stat.S_IRGRP | stat.S_IRWXO)
        # uuid生成不重复的字符串
        file_name = str(uuid.uuid4()).replace("-", "") + "." + ext
        file.save("{0}/{1}".format(save_dir, file_name))

        model_image = Image()
        model_image.file_key = file_dir + "/" + file_name
        model_image.created_time = getCurrentData()
        db.session.add(model_image)
        db.session.commit()

        resp['data'] = {'file_key': model_image.file_key}
        return resp
Ejemplo n.º 7
0
def ops():
    resp = {'code': 200, 'msg':'操作成功', 'data':{}}
    req = request.values
    id = req['id'] if 'id' in req else 0
    act = req['act'] if 'act' in req else ''
    if not id:
        resp['code'] = -1
        resp['msg'] = '请选择要操作的账号'
        return jsonify(resp)

    if act not in ['remove', 'recover']:
        resp['code'] = -1
        resp['msg'] = '操作有误,请重试'
        return jsonify(resp)

    member_info = Member.query.filter_by(id=id).first()
    if not member_info:
        resp['code'] = -1
        resp['msg'] = '会员不存在'
        return jsonify(resp)

    if act == 'remove':
        member_info.status = 0
    elif act == 'recover':
        member_info.status = 1
    member_info.updated_time = getCurrentData()
    db.session.add(member_info)
    db.session.commit()

    return jsonify(resp)
Ejemplo n.º 8
0
def memberShare():
    resp = {'code': 200, 'msg': '操作成功~', 'data': {}}
    req = request.values
    url = req['url'] if 'url' in req else ''
    member_info = g.member_info  # 拦截器的方法,判断
    model_share = WxShareHistory()
    if member_info:
        model_share.member_id = member_info.id

    model_share.share_url = url
    model_share.created_time = getCurrentData()
    db.session.add(model_share)
    db.session.commit()
    return jsonify(resp)


# @route_api.route("/member/info")
# def memberInfo():
#     resp = {'code': 200, 'msg': '操作成功~', 'data': {}}
#     member_info = g.member_info
#     resp['data']['info'] = {
#         "nickname":member_info.nickname,
#         "avatar_url":member_info.avatar
#     }
#     return jsonify(resp)
Ejemplo n.º 9
0
def catOps():
    resp = {'code': 200, 'msg': 'ok', 'data': {}}
    req = request.values
    id = req['id'] if 'id' in req else 0
    act = req['act'] if 'act' in req else ''

    if not id:
        resp['code'] = -1
        resp['msg'] = 'please choose'
        return jsonify(resp)

    if act not in ['remove', 'recover']:
        resp['code'] = -1
        resp['msg'] = '404 404 404 404'
        return jsonify(resp)

    food_cat_info = FoodCat.query.filter_by(id=id).first()

    if not food_cat_info:
        resp['code'] = -1
        resp['msg'] = 'is not user'
        return jsonify(resp)

    if act == 'remove':
        food_cat_info.status = 0

    elif act == 'recover':
        food_cat_info.status = 1
    food_cat_info.updata_time = getCurrentData()
    db.session.add(food_cat_info)
    db.session.commit()
    return jsonify(resp)
Ejemplo n.º 10
0
def ops():
    resp = {'code': 200, 'msg': '操作成功~~', 'data': {}}
    req = request.values

    id = req['id'] if 'id' in req else 0
    act = req['act'] if 'act' in req else ''

    if not id:
        resp['code'] = -1
        resp['msg'] = "请选择要操作的账号~~"
        return jsonify(resp)

    if act not in ['remove', 'recover']:
        resp['code'] = -1
        resp['msg'] = "操作有误,请重试~~"
        return jsonify(resp)

    food_info = Food.query.filter_by(id=id).first()
    if not food_info:
        resp['code'] = -1
        resp['msg'] = "指定美食不存在~~"
        return jsonify(resp)

    if act == "remove":
        food_info.status = 0
    elif act == "recover":
        food_info.status = 1

    food_info.updated_time = getCurrentData()
    db.session.add(food_info)
    db.session.commit()
    return jsonify(resp)
Ejemplo n.º 11
0
def catSet():
    """
        菜品分类的 编辑和添加(编辑会查到菜的id修改信息,添加不到id)
    """
    if request.method == "GET":
        resp_data = {}
        req = request.args
        id = int(req.get("id", 0))
        info = None  # 因为如果是添加信息,那么上个页面,就不会传回id,所以为None,进入添加账号页面。否则点击编辑就传回id,进入修改信息页面
        if id:
            info = FoodCat.query.filter_by(
                id=id).first()  # filter_by不用写类,他会自动区分的

        resp_data['info'] = info  # 统一渲染的 resp_data(json)里面,将user_info放进去
        resp_data['current'] = 'cat'
        return ops_render("food/cat_set.html", resp_data)

    resp = {'code': 200, 'msg': u"操作成功", 'data': {}}
    # 获取登录变量
    req = request.values  # 所有的请求变量,放到这个数组里

    id = req['id'] if 'id' in req else 0  # id 是用来判断是增加用户信息,还是修改用户信息
    name = req['name'] if 'name' in req else ''  # 三元表达式
    weight = int(req['weight']) if ('weight' in req
                                    and int(req['weight']) > 0) else ''

    if name is None or len(name) < 2 or len(name) > 12:  # 进行参数判断
        resp['code'] = -1
        resp['msg'] = "请输入符合规范的分类名称"
        return jsonify(resp)  # json 格式的转换

    food_cat_info = FoodCat.query.filter_by(
        id=id).first()  # 判断食品 id是否存在。如果存在,那么 modle_use,就是这个食品的信息。set页面为修改用户信息
    if food_cat_info:
        modle_cat_info = food_cat_info
    else:  # 否则,就是这个uid不存在。那么久为增加用户信息界面
        modle_cat_info = FoodCat()
        modle_cat_info.created_time = getCurrentData(
        )  # 增加用户信息时,created_time才改变

    modle_cat_info.name = name
    modle_cat_info.weight = weight
    modle_cat_info.updated_time = getCurrentData()

    db.session.add(modle_cat_info)  # 数据库添加数据,统一提交
    db.session.commit()
    return jsonify(resp)  # 返回信息,更改成功
Ejemplo n.º 12
0
 def setItems(member_id=0, food_id=0, number=0):
     if member_id < 1 or food_id < 1 or number < 1:
         return False
     cart_info = MemberCart.query.filter_by(food_id=food_id, member_id=member_id).first()
     if cart_info:
         model_cart = cart_info
     else:
         model_cart = MemberCart()
         model_cart.member_id = member_id
         model_cart.created_time = getCurrentData()
     app.logger.info('正在存储')
     model_cart.food_id = food_id
     model_cart.quantity = number
     model_cart.updated_time = getCurrentData()
     db.session.add(model_cart)
     db.session.commit()
     return True
Ejemplo n.º 13
0
 def addErrorLog(content):
     target = AppErrorLog()
     target.target_url = request.url
     target.referer_url = request.referrer
     target.query_params = json.dumps(request.values.to_dict())
     target.content = content
     target.created_time = getCurrentData()
     db.session.add(target)
     db.session.commit()
     pass
Ejemplo n.º 14
0
    def setItems( member_id = 0,food_id = 0,number = 0 ):  # 用户id,商品id,添加数量
        if member_id < 1 or food_id < 1 or number < 1:  # 如果任何一个值小于1
            return False

        # 添加和更新,判断这个信息是否存在(用户和商品 id 是否相同)
        cart_info = MemberCart.query.filter_by( food_id = food_id, member_id= member_id ).first()
        if cart_info:  # 如果购物车数据表,有这个添加信息。就是set更新
            model_cart = cart_info
        else:  # 没有就是,添加新的信息
            model_cart = MemberCart()
            model_cart.member_id = member_id
            model_cart.created_time = getCurrentData()

        model_cart.food_id = food_id
        model_cart.quantity = number
        model_cart.updated_time = getCurrentData()
        db.session.add(model_cart)
        db.session.commit()
        return True
Ejemplo n.º 15
0
def memberShare():
    resp = {'code': 200, 'msg': '操作成功~', 'data': {}}
    req = request.values
    url = req['url'] if 'url' in req else ''
    member_info = g.member_info
    model_share = WxShareHistory()
    if member_info:
        model_share.member_id = member_info.id
    model_share.share_url = url
    model_share.created_time = getCurrentData()
    db.session.add(model_share)
    db.session.commit()
    return jsonify(resp)
Ejemplo n.º 16
0
 def addAccessLog():
     target = AppAccessLog()
     target.target_url = request.url
     target.referer_url = request.referrer
     target.ip = request.remote_addr
     target.query_params = json.dumps(request.values.to_dict())
     if 'current_user' in g and g.current_user is not None:
         target.uid = g.current_user.uid
     target.ua = request.headers.get("User-Agent")
     target.created_time = getCurrentData()
     db.session.add(target)
     db.session.commit()
     return True
Ejemplo n.º 17
0
def catSet():
    if request.method == "GET":
        resp_data = {}
        req = request.args
        print("----------")
        print(req)
        id = int(req.get("id", 0))
        info = None
        if id:
            info = FoodCat.query.filter_by(id=id).first()
        resp_data['info'] = info
        resp_data['current'] = 'cat'
        return ops_render("food/cat_set.html", resp_data)

    resp = {'code': 200, 'msg': '操作成功~~', 'data': {}}
    req = request.values

    id = req['id'] if 'id' in req else 0
    name = req['name'] if 'name' in req else ''
    weight = int(req['weight']) if ('weight' in req
                                    and int(req['weight']) > 0) else 1

    if name is None or len(name) < 1:
        resp['code'] = -1
        resp['msg'] = "请输入符合规范的分类名称~~"
        return jsonify(resp)

    food_cat_info = FoodCat.query.filter_by(id=id).first()
    if food_cat_info:
        model_food_cat = food_cat_info
    else:
        model_food_cat = FoodCat()
        model_food_cat.created_time = getCurrentData()
    model_food_cat.name = name
    model_food_cat.weight = weight
    model_food_cat.updated_time = getCurrentData()
    db.session.add(model_food_cat)
    db.session.commit()
    return jsonify(resp)
Ejemplo n.º 18
0
def set():
    """
     会员修改信息页面
    """
    if request.method == "GET":
        resp_data = {}
        req = request.args
        id = int(req.get("id", 0))  # 默认值传 0
        reback_url = UrlManager.buildUrl("/member/index")  # 反回列表页面

        if id < 1:
            return redirect(reback_url)  # 回到列表页面

        info = Member.query.filter_by(id=id).first()  # 查询这个用户id是否存在
        if not info:  # 如果没有这个用户信息
            return redirect(reback_url)

        if info.status != 1:  # 如果 会员用户的 状态!=1,也不可以进入编辑页面
            return redirect(reback_url)

        resp_data['info'] = info
        resp_data['current'] = 'index'  # 光标

        return ops_render("member/set.html", resp_data)

    # Malibu country
    resp = {'code': 200, 'msg': u"操作成功", 'data': {}}
    # 获取登录变量
    req = request.values  # 所有的请求变量,放到这个数组里

    id = req['id'] if 'id' in req else 0  # 获取在 req 里面的 会员id,没有就为0
    nickname = req['nickname'] if 'nickname' in req else ''  # 三元表达式

    if nickname is None or len(nickname) < 2 or len(nickname) > 20:  # 进行参数判断
        resp['code'] = -1
        resp['msg'] = "请输入符合规范的姓名"
        return jsonify(resp)  # json 格式的转换

    member_info = Member.query.filter_by(
        id=id).first()  # 判断用户 id是否存在。如果存在,那么 modle_use,就是这个用户的信息。set页面为修改用户信息
    if not member_info:
        resp['code'] = -1
        resp['msg'] = "该会员信息不存在"
        return jsonify(resp)  # json 格式的转换

    member_info.nickname = nickname
    member_info.updated_time = getCurrentData()

    db.session.add(member_info)  # 数据库添加数据,统一提交
    db.session.commit()
    return jsonify(resp)  # 返回信息,更改成功
Ejemplo n.º 19
0
    def addErrorLog(content):  # content 是错误拦截器传回的e
        """
            错误记录
        """
        target = AppErrorLog()
        target.target_url = request.url  # 请求的链接
        target.referer_url = request.referrer
        target.ip = request.remote_addr  # 远程地址
        target.query_params = json.dumps(request.values.to_dict(
        ))  # 使用json的方式传进来。dumps将字符串解析成json。to_dict():请求的数据转化成字典
        target.content = content
        target.created_time = getCurrentData()

        db.session.add(target)
        db.session.commit()
        return True
Ejemplo n.º 20
0
    def addAccessLog():
        """
            访问记录
        """
        target = AppAccessLog()
        target.target_url = request.url  # 请求的链接
        target.referer_url = request.referrer
        target.ip = request.remote_addr  # 远程地址
        target.query_params = json.dumps(request.values.to_dict(
        ))  # 使用json的方式传进来。dumps将字符串解析成json。to_dict():请求的数据转化成字典
        if 'current_user' in g and g.current_user is not None:
            target.uid = g.current_user.uid
        target.ua = request.headers.get("User-Agent")  # 用户头信息
        target.created_time = getCurrentData()

        db.session.add(target)
        db.session.commit()
        return True
Ejemplo n.º 21
0
    def setStockChangeLog(food_id=0, quantity=0, note=''):  # 商品id,变更的数量,备注信息

        if food_id < 1:
            return False

        food_info = Food.query.filter_by(id=food_id).first()
        if not food_info:
            return False

        model_stock_change = FoodStockChangeLog()
        model_stock_change.food_id = food_id
        model_stock_change.unit = quantity
        model_stock_change.total_stock = food_info.stock
        model_stock_change.note = note
        model_stock_change.created_time = getCurrentData()
        db.session.add(model_stock_change)
        db.session.commit()
        return True
Ejemplo n.º 22
0
def CatOps():
    """
        删除、恢复账号
    """
    ## 都是用json,ajax提交,所以定义头部
    resp = {'code': 200, 'msg': u"操作成功", 'data': {}}
    req = request.values

    # 操作过程
    id = req['id'] if 'id' in req else 0
    act = req['act'] if 'act' in req else ''
    if not id:  # 如果没有id
        resp['code'] = -1
        resp['msg'] = "请选择要操作的菜品分类"
        return jsonify(resp)  # json 格式的转换

    if act not in ['remove', 'recover']:  # 这样写,防止伪造js(如果act状态里面)
        resp['code'] = -1
        resp['msg'] = "操作有误,请重试"
        return jsonify(resp)  # json 格式的转换

    food_cat_info = FoodCat.query.filter_by(
        id=id).first()  # 根据id查询菜品分类信息是否存在。提示信息!
    if not food_cat_info:
        resp['code'] = -1
        resp['msg'] = "指定菜品分类不存在"
        return jsonify(resp)  # json 格式的转换

    ## 删除、恢复,其实就是状态的改变
    if act == "remove":  #如果是删除动作
        food_cat_info.status = 0  # 将这个用户的状态status,改为0。就不显示了
    elif act == "recover":  # 如果是恢复动作
        food_cat_info.status = 1  # 将这个用户的状态status,改为1。就显示了

    food_cat_info.updated_time = getCurrentData()  # 每次更新数据时,要记得更新时间
    db.session.add(food_cat_info)  # 数据库添加数据,统一提交
    db.session.commit()
    return jsonify(resp)  # 返回信息,更改成功
Ejemplo n.º 23
0
def add():
    req=request.values
    username=req['username'] if 'username' in req else ""
    password = req['password'] if 'password' in req else ""
    email = req['email'] if 'email' in req else ""
    salt=UserService.geneSalt()

    module_user=YiAdmin()
    module_user.username=username
    module_user.password=UserService.genePwd(password,salt)
    module_user.email=email
    module_user.level='1'
    module_user.state='2'
    module_user.admin='3'
    module_user.login_salt=salt
    module_user.lasttime=getCurrentData()
    try:
        db.session.add(module_user)
        db.session.commit()
    except Exception as e:
        return RespUtils.error('添加失败', e)

    return  RespUtils.success('添加成功')
Ejemplo n.º 24
0
def set():
    if request.method == 'GET':
        resp_data = {}
        req = request.args
        id = int(req.get('id', 0))
        reback_url = UrlManager.buildUrl('/member/index')
        if id < 1:
            return redirect(reback_url)

        info = Member.query.filter_by(id=id).first()
        if not info:
            return redirect(reback_url)

        if info.status != 1:
            return redirect(reback_url)
        resp_data['info'] = info
        resp_data['current'] = 'index'

        return ops_render("member/set.html", resp_data)
    resp = {'code': 200, 'msg': 'OK', 'data': {}}
    req = request.values
    id = req['id'] if 'id' in req else 0
    nickname = req['nickname'] if 'nickname' in req else ''
    if nickname is None or len(nickname) < 1:
        resp['code'] = -1
        resp['msg'] = "请输入符合规范的姓名~~"
        return jsonify(resp)
    member_info = Member.query.filter_by(id=id).first()
    if not member_info:
        resp['code'] = -1
        resp['msg'] = "指定会员不存在~~"
        return jsonify(resp)
    member_info.nickname = nickname
    member_info.updated_time = getCurrentData()
    db.session.add(member_info)
    db.session.commit()
    return jsonify(resp)
Ejemplo n.º 25
0
def ops():
    resp = {'code': 200, 'msg': '操作成功~~', 'data': {}}
    req = request.values

    id = req['id'] if 'id' in req else 0
    act = req['act'] if 'act' in req else ''
    if not id:
        resp['code'] = -1
        resp['msg'] = "请选择要操作的账号~~"
        return jsonify(resp)

    if act not in ['remove', 'recover']:
        resp['code'] = -1
        resp['msg'] = "操作有误,请重试~~"
        return jsonify(resp)

    user_info = User.query.filter_by(uid=id).first()
    if not user_info:
        resp['code'] = -1
        resp['msg'] = "指定账号不存在~~"
        return jsonify(resp)

    if act == "remove":
        user_info.status = 0
    elif act == "recover":
        user_info.status = 1

    if user_info and user_info.uid == 1:
        resp['code'] = -1
        resp['msg'] = "该用户是演示账号,不准操作账号~~"
        return jsonify(resp)

    user_info.update_time = getCurrentData()
    db.session.add(user_info)
    db.session.commit()
    return jsonify(resp)
Ejemplo n.º 26
0
def set():
    if request.method == "GET":
        resp_data = {}
        req = request.args
        id = int(req.get('id', 0))

        info = Food.query.filter_by(id=id).first()
        if info and info.status != 1:
            return redirect(UrlManager.buildUrl("/food/index"))

        cat_list = FoodCat.query.all()

        resp_data['info'] = info
        resp_data['cat_list'] = cat_list
        resp_data['current'] = 'index'

        return ops_render("food/set.html", resp_data)

    resp = {'code': 200, 'msg': '操作成功~~', 'data': {}}
    req = request.values
    id = int(req['id']) if 'id' in req and req['id'] else 0
    cat_id = int(req['cat_id']) if 'cat_id' in req else 0
    name = req['name'] if 'name' in req else ''
    price = req['price'] if 'price' in req else ''
    main_image = req['main_image'] if 'main_image' in req else ''
    summary = req['summary'] if 'summary' in req else ''
    stock = int(req['stock']) if 'stock' in req else ''
    tags = req['tags'] if 'tags' in req else ''

    if cat_id < 1:
        resp['code'] = -1
        resp['msg'] = "请选择分类~~"
        return jsonify(resp)

    if name is None or len(name) < 1:
        resp['code'] = -1
        resp['msg'] = "请输入符合规范的名称~~"
        return jsonify(resp)

    if not price or len(price) < 1:
        resp['code'] = -1
        resp['msg'] = "请输入符合规范的售卖价格~~"
        return jsonify(resp)

    price = Decimal(price).quantize(Decimal('0.00'))
    if price <= 0:
        resp['code'] = -1
        resp['msg'] = "请输入符合规范的售卖价格~~"
        return jsonify(resp)

    if main_image is None or len(main_image) < 3:
        resp['code'] = -1
        resp['msg'] = "请上传封面图~~"
        return jsonify(resp)

    if summary is None or len(summary) < 3:
        resp['code'] = -1
        resp['msg'] = "请输入图书描述,并不能少于10个字符~~"
        return jsonify(resp)

    if stock < 1:
        resp['code'] = -1
        resp['msg'] = "请输入符合规范的库存量~~"
        return jsonify(resp)

    if tags is None or len(tags) < 1:
        resp['code'] = -1
        resp['msg'] = "请输入标签,便于搜索~~"
        return jsonify(resp)

    food_info = Food.query.filter_by(id=id).first()
    before_stock = 0
    if food_info:
        model_food = food_info
        before_stock = model_food.stock
    else:
        model_food = Food()
        model_food.status = 1
        model_food.created_time = getCurrentData()

    model_food.cat_id = cat_id
    model_food.name = name
    model_food.price = price
    model_food.main_image = main_image
    model_food.summary = summary
    model_food.stock = stock
    model_food.tags = tags
    model_food.updated_time = getCurrentData()

    db.session.add(model_food)
    ret = db.session.commit()

    FoodService.setStockChangeLog(model_food.id,
                                  int(stock) - int(before_stock), "后台修改")
    return jsonify(resp)
Ejemplo n.º 27
0
    def createOrder(self,
                    member_id,
                    items=None,
                    params=None):  # 创建订单(哪个用户,商品列表,params额外字段[留言] )
        """
        实现下单并发,库存减少
        :param member_id:
        :param items:
        :param params:
        :return:
        """
        resp = {'code': 200, 'msg': '操作成功~', 'data': {}}
        pay_price = decimal.Decimal(0.00)  # 商品总价格
        continue_cnt = 0
        food_ids = []
        for item in items:  # 遍历所有下单的商品
            if decimal.Decimal(item['price']) < 0:  # 如果有的商品价格<0。那么统计次数,并且跳过
                continue_cnt += 1
                continue

            pay_price = pay_price + decimal.Decimal(item['price']) * int(
                item['number'])  # 此时的,商品总价格。就是,初始价格0.00 + 上面跳过的商品价格 * 下单数量
            food_ids.append(item['id'])  # 在这里面添加,通过的商品的 id

        if continue_cnt >= len(items):  # 如果跳过的次数 >= 下单商品的数量。说明没有选择商品
            resp['code'] = -1
            resp['msg'] = '商品items为空~~'
            return resp

        yun_price = params[
            'yun_price'] if params and 'yun_price' in params else 0
        note = params['note'] if params and 'note' in params else ''
        express_address_id = params[
            'express_address_id'] if params and 'express_address_id' in params else 0
        express_info = params[
            'express_info'] if params and 'express_info' in params else {}
        yun_price = decimal.Decimal(yun_price)
        total_price = pay_price + yun_price

        # 并发处理 乐观锁和悲观锁。这里采用的是观锁。(悲观锁:锁数据表行记录。乐观锁:数据表增加一个字段,每次更新时对它进行判断 )
        try:
            # 为了防止并发库存出问题了,我们坐下selectfor update, 这里可以给大家演示下
            tmp_food_list = db.session.query(Food).filter(Food.id.in_(food_ids)) \
                .with_for_update().all()  # 锁定所有本次下单的商品id,行记录

            tmp_food_stock_mapping = {}  # 临时的商品库存 map,方便对比
            for tmp_item in tmp_food_list:
                tmp_food_stock_mapping[
                    tmp_item.id] = tmp_item.stock  # 被锁定的商品 库存

            model_pay_order = PayOrder()
            model_pay_order.order_sn = self.geneOrderSn()  # 随机订单号,通过随机算法算出
            model_pay_order.member_id = member_id
            model_pay_order.total_price = total_price
            model_pay_order.yun_price = yun_price
            model_pay_order.pay_price = pay_price
            model_pay_order.note = note  # 备注信息
            model_pay_order.status = -8  # 默认状态:-8待付款
            model_pay_order.express_status = -8  # 待支付
            model_pay_order.express_address_id = express_address_id
            model_pay_order.express_info = json.dumps(express_info)
            model_pay_order.updated_time = model_pay_order.created_time = getCurrentData(
            )
            db.session.add(model_pay_order)
            db.session.flush()

            for item in items:  # 第一次判断,剩下的商品(跳出的商品)
                tmp_left_stock = tmp_food_stock_mapping[item['id']]

                if decimal.Decimal(item['price']) < 0:  # 如果是价格<=0,就停止本次操作,继续
                    continue

                if int(item['number']) > int(tmp_left_stock):  # 如果下单的商品数量 > 库存
                    raise Exception("您购买的这美食太火爆了,剩余:%s,您购买%s~~" %
                                    (tmp_left_stock, item['number']))

                tmp_ret = Food.query.filter_by(id=item['id']).update(
                    {"stock":
                     int(tmp_left_stock) - int(item['number'])})  # 更新库存
                if not tmp_ret:
                    raise Exception("下单失败请重新下单")

                tmp_pay_item = PayOrderItem()  # 生成订单
                tmp_pay_item.pay_order_id = model_pay_order.id
                tmp_pay_item.member_id = member_id
                tmp_pay_item.quantity = item['number']  # 下单数量
                tmp_pay_item.price = item['price']  # 商品单价
                tmp_pay_item.food_id = item['id']  # 商品id
                tmp_pay_item.note = note  # 备注信息
                tmp_pay_item.updated_time = tmp_pay_item.created_time = getCurrentData(
                )
                db.session.add(tmp_pay_item)
                db.session.flush()

                FoodService.setStockChangeLog(item['id'], -item['number'],
                                              "在线购买")  # 商品变更记录。商品id,-数量,备注
            db.session.commit()  # 直到完成本次提交,行锁才解开
            resp['data'] = {  # 下单成功,返回数据
                'id': model_pay_order.id,
                'order_sn': model_pay_order.order_sn,
                'total_price': str(total_price)
            }
        except Exception as e:
            pass
            db.session.rollback()  # 如果出现异常,数据回滚,回到操作前的状态
            print("*" * 50, e)
            resp['code'] = -1
            resp['msg'] = "下单失败请重新下单"
            resp['msg'] = str(e)
            return resp
        return resp
Ejemplo n.º 28
0
    def createOrder(self, member_id, items=None, params=None):
        resp = {"code": 200, "msg": "操作成功", "data": {}}
        pay_price = decimal.Decimal(0.00)
        continue_cnt = 0
        foods_id = []
        for item in items:
            if decimal.Decimal(item['price']) < 0:
                continue_cnt += 1
                continue
            pay_price = pay_price + decimal.Decimal(item['price']) * int(
                item['number'])
            foods_id.append(item['id'])

        if continue_cnt >= len(items):
            resp['code'] = -1
            resp['msg'] = '商品items为空'
            return resp
        yun_price = params.get('yun_price', 0)
        note = params.get('note', '')
        yun_price = decimal.Decimal(yun_price)
        total_price = pay_price + yun_price
        try:
            # 锁
            tmp_food_list = db.session.query(Food).filter(
                Food.id.in_(foods_id)).with_for_update().all()
            # 创建列表得到{food.id: 库存}
            tmp_food_stock_mapping = {}
            for tmp_item in tmp_food_list:
                tmp_food_stock_mapping[tmp_item.id] = tmp_item.stock

            model_pay_order = PayOrder()
            model_pay_order.order_sn = self.geneOrderSn()
            model_pay_order.member_id = member_id
            model_pay_order.total_price = total_price
            model_pay_order.yun_price = yun_price
            model_pay_order.pay_price = pay_price
            model_pay_order.note = note
            model_pay_order.status = -8
            model_pay_order.express_status = -8
            # model_pay_order.express_address_id = express_address_id
            # model_pay_order.express_info = json.dumps(express_info)
            model_pay_order.updated_time = model_pay_order.created_time = getCurrentData(
            )
            db.session.add(model_pay_order)
            # db.session.flush()
            for item in items:
                tmp_left_stock = tmp_food_stock_mapping[item['id']]

                if decimal.Decimal(item['price']) < 0:
                    continue
                # 库存不够
                if int(item['number']) > int(tmp_left_stock):
                    raise Exception("您购买的这美食太火爆了,剩余:%s,你购买%s~~" %
                                    (tmp_left_stock, item['number']))

                # 库存减少
                tmp_ret = Food.query.filter_by(id=item['id']).update(
                    {"stock": int(tmp_left_stock) - int(item['number'])})
                if not tmp_ret:
                    raise Exception("下单失败请重新下单")

                tmp_pay_item = PayOrderItem()
                tmp_pay_item.pay_order_id = model_pay_order.id
                tmp_pay_item.member_id = member_id
                tmp_pay_item.quantity = item['number']
                tmp_pay_item.price = item['price']
                tmp_pay_item.food_id = item['id']
                tmp_pay_item.note = note
                tmp_pay_item.updated_time = tmp_pay_item.created_time = getCurrentData(
                )
                db.session.add(tmp_pay_item)
                # db.session.flush()
                # 修改库存
                FoodService.setStockChangeLog(item['id'], -item['number'],
                                              "在线购买")
            db.session.commit()
            resp['data'] = {
                'id': model_pay_order.id,
                'order_sn': model_pay_order.order_sn,
                'total_price': str(total_price)
            }
        except Exception as e:
            db.session.rollback()
            print(e)
            resp['code'] = -1
            resp['msg'] = "下单失败请重新下单"
            resp['msg'] = str(e)
            return resp
        return resp
Ejemplo n.º 29
0
def set():
    default_pwd = '******'
    if request.method == 'GET':
        resp_data = {}
        req = request.args
        uid = int(req.get('id', 0))
        info = None
        if uid:
            info = User.query.filter_by(uid=uid).first()
        resp_data['info'] = info
        return ops_render("account/set.html", resp_data)

    resp = {'code': 200, 'msg': '操作成功', 'data': {}}
    req = request.values

    id = req['id'] if 'id' in req else 0
    nickname = req['nickname'] if 'nickname' in req else ''
    mobile = req['mobile'] if 'mobile' in req else ''
    email = req['email'] if 'email' in req else ''
    login_name = req['login_name'] if 'login_name' in req else ''
    login_pwd = req['login_pwd'] if 'login_pwd' in req else ''

    if nickname is None or len(nickname) < 1:
        resp['code'] = -1
        resp['msg'] = '请输入符合规范的用户名'
        return jsonify(resp)

    if mobile is None or len(mobile) < 1:
        resp['code'] = -1
        resp['msg'] = '请输入符合规范的手机号'
        return jsonify(resp)

    if email is None or len(email) < 1:
        resp['code'] = -1
        resp['msg'] = '请输入符合规范的邮箱'
        return jsonify(resp)

    if login_name is None or len(login_name) < 1:
        resp['code'] = -1
        resp['msg'] = '请输入符合规范的登录名'
        return jsonify(resp)

    if login_pwd is None or len(login_pwd) < 1:
        resp['code'] = -1
        resp['msg'] = '请输入符合规范的密码'
        return jsonify(resp)

    has_in = User.query.filter(User.login_name == login_name,
                               User.uid != id).first()
    if has_in:
        resp['code'] = -1
        resp['msg'] = '换一个登录名去'
        return jsonify(resp)

    user_info = User.query.filter_by(uid=id).first()
    if user_info:
        model_user = user_info
    else:
        model_user = User()
        model_user.created_time = getCurrentData()
        model_user.login_salt = UserService.geneSalt()

    model_user.nickname = nickname
    model_user.mobile = mobile
    model_user.email = email
    model_user.login_name = login_name
    if login_pwd != default_pwd:
        model_user.login_pwd = UserService.genePwd(login_pwd,
                                                   model_user.login_salt)
    model_user.updated_time = getCurrentData()

    db.session.add(model_user)
    db.session.commit()
    return jsonify(resp)
Ejemplo n.º 30
0
def set():
    """
        修改个人信息页面、添加账号信息页面
    """
    default_pwd = "******"
    if request.method == "GET":
        resp_data = {}
        req = request.args
        uid = int(req.get("id", 0))
        info = None  # 因为如果是添加信息,那么上个页面,就不会传回id,所以为None,进入添加账号页面。否则点击编辑就传回id,进入修改信息页面
        if uid:
            info = User.query.filter_by(
                uid=uid).first()  # filter_by不用写类,他会自动区分的
        resp_data['info'] = info  # 统一渲染的 resp_data(json)里面,将user_info放进去
        return ops_render("account/set.html", resp_data)

    resp = {'code': 200, 'msg': u"操作成功", 'data': {}}
    # 获取登录变量
    req = request.values  # 所有的请求变量,放到这个数组里

    id = req['id'] if 'id' in req else 0  # id 是用来判断是增加用户信息,还是修改用户信息
    nickname = req['nickname'] if 'nickname' in req else ''  # 三元表达式
    mobile = req['mobile'] if 'mobile' in req else ''
    email = req['email'] if 'email' in req else ''
    login_name = req['login_name'] if 'login_name' in req else ''
    login_pwd = req['login_pwd'] if 'login_pwd' in req else ''

    if nickname is None or len(nickname) < 2 or len(nickname) > 15:  # 进行参数判断
        resp['code'] = -1
        resp['msg'] = "请输入符合规范的姓名"
        return jsonify(resp)  # json 格式的转换

    if mobile is None or not re.match(REGEX_MOBILE, mobile):  # 进行参数判断
        resp['code'] = -1
        resp['msg'] = "请输入符合规范的手机号码"
        return jsonify(resp)  # json 格式的转换

    if email is None or not re.match(REGEX_Email, email):  # 进行参数判断
        resp['code'] = -1
        resp['msg'] = "请输入符合规范的邮箱"
        return jsonify(resp)  # json 格式的转换

    if login_name is None or not re.match(REGEX_LOGIN_NAME,
                                          login_name):  # 进行参数判断
        resp['code'] = -1
        resp['msg'] = "请输入符合规范的登录名"
        return jsonify(resp)  # json 格式的转换

    if login_pwd is None or len(login_pwd) < 6 or len(
            login_pwd) > 15:  # 进行参数判断
        resp['code'] = -1
        resp['msg'] = "请输入符合规范的登录密码"
        return jsonify(resp)  # json 格式的转换

    has_in = User.query.filter(User.login_name == login_name,
                               User.uid != id).first()
    # login_name判断用户是否存在。User.uid != id:这个表明是该用户id不存在,即为增加用户信息。filter支持的方式更多一点。filter_by只能传一个json

    if has_in:  # 如果用户名已经存在了
        resp['code'] = -1
        resp['msg'] = "该登录名已存在,请重新输入"
        return jsonify(resp)  # json 格式的转换

    user_info = User.query.filter_by(
        uid=id).first()  # 判断用户 id是否存在。如果存在,那么 modle_use,就是这个用户的信息。set页面为修改用户信息
    if user_info:
        modle_use = user_info
    else:  # 否则,就是这个uid不存在。那么久为增加用户信息界面
        modle_use = User()
        modle_use.created_time = getCurrentData()  # 增加用户信息时,created_time才改变
        modle_use.login_salt = UserService.geneSalt(
        )  # geneSalt即数据库salt字段, 自定义的加密规则。增加用户信息,才会生成salt

    modle_use.nickname = nickname
    modle_use.mobile = mobile
    modle_use.email = email
    modle_use.login_name = login_name
    if login_pwd != default_pwd:  # 如果传回来的密码value,不是default密码,那么就改密码,反之不改密码。
        modle_use.login_pwd = UserService.genePwd(
            login_pwd, modle_use.login_salt)  # 加密后的密码,就是前面定义的,通过密码和 salt进行加密
        resp['msg'] = "操作成功,登录用户 %s 的密码为:%s" % (login_name, login_pwd)
    modle_use.updated_time = getCurrentData()

    db.session.add(modle_use)  # 数据库添加数据,统一提交
    db.session.commit()
    return jsonify(resp)  # 返回信息,更改成功