Example #1
0
 def remove_todoList(cls, bid):
     todoList = cls.query.filter_by(id=bid, delete_time=None).first()
     if todoList is None:
         raise NotFound(msg='没有找到相关数据')
     # 删除图书,软删除
     todoList.delete(commit=True)
     return True
Example #2
0
 def clear(cls, member_id):
     models = cls.query.filter_by(member_id=member_id).all()
     if not models:
         raise NotFound(msg='购物车已空,不能再清空')
     for model in models:
         model.hard_delete(commit=True)
     return True
Example #3
0
 def get_paginate_models(cls,
                         start,
                         count,
                         q=None,
                         soft=True,
                         *,
                         throw=False):
     """查询分页数据(支持搜索)"""
     statement = cls.query.filter_by(soft=soft)
     if q:
         q = '%{}%'.format(q)
         statement = statement.filter(cls.name.ilike(q))
     total = statement.count()
     models = statement.order_by(
         cls.id.desc()).offset(start).limit(count).all()
     if not models:
         if not throw:
             return []
         else:
             raise NotFound(msg='相关资源未添加或已隐藏')
     return {
         'start': start,
         'count': count,
         'total': total,
         'models': models
     }
Example #4
0
 def get_with_products(cls, tid, soft=True, *, throw=False):
     from app.models.theme_product import ThemeProduct
     from app.models.product import Product
     head_img = aliased(File)
     product_img = aliased(File)
     data = db.session.query(cls, head_img, product_img, ThemeProduct, Product).filter_by(soft=soft).filter(
         cls.head_img_id == head_img.id,
         Product.img_id == product_img.id,
         cls.id == ThemeProduct.theme_id,
         ThemeProduct.product_id == Product.id,
         cls.id == tid
     ).all()
     if not data:
         if not throw:
             return []
         else:
             raise NotFound(msg='相关主题不存在商品')
     res = []
     for theme, head_img, product_img, _, product in data:
         theme.products = getattr(theme, 'products', [])
         theme.head_img = cls.get_file_url(head_img.path)
         product.image = cls.get_file_url(product_img.path)
         theme.products.append(product)
         res.append(theme)
     res = res[0]
     res._fields.extend(['head_img', 'products'])
     return res
Example #5
0
def update_user(uid):
    form = UpdateUserInfoForm().validate_for_api()

    user = manager.user_model.get(id=uid)
    if user is None:
        raise NotFound("用户不存在")
    if user.email != form.email.data:
        exists = manager.user_model.get(email=form.email.data)
        if exists:
            raise ParameterError("邮箱已被注册,请重新输入邮箱")
    with db.auto_commit():
        user.email = form.email.data
        group_ids = form.group_ids.data
        # 清空原来的所有关联关系
        manager.user_group_model.query.filter_by(user_id=user.id).delete(
            synchronize_session=False)
        # 根据传入分组ids 新增关联记录
        user_group_list = list()
        # 如果没传分组数据,则将其设定为 guest 分组
        if len(group_ids) == 0:
            group_ids = [
                manager.group_model.get(level=GroupLevelEnum.GUEST.value).id
            ]
        for group_id in group_ids:
            user_group = manager.user_group_model()
            user_group.user_id = user.id
            user_group.group_id = group_id
            user_group_list.append(user_group)
        db.session.add_all(user_group_list)
    return Success("操作成功")
Example #6
0
 def remove_user(cls, vid):
     User = cls.query.filter_by(id=vid, delete_time=None).first()
     if User is None:
         raise NotFound(msg='没有找到相关用户')
     # 删除用户,软删除
     User.hard_delete(commit=True)
     return True
Example #7
0
 def delete_user(cls, form):
     User = cls.query.filter_by(username=form.username.data,
                                delete_time=None).first()
     if User is None:
         raise NotFound(msg='没有找到相关用户')
     User.hard_delete(commit=True)
     return True
Example #8
0
 def get_all(cls, start, count):
     Info = cls.query.filter_by(delete_time=None).order_by(
         OpenVPNLogInfo.starting_time.desc()).offset(start).limit(
             count).all()
     if not Info:
         raise NotFound(msg='没有找到相关登入信息')
     return Info
Example #9
0
    def pay(self, member_id, openid, order_id):
        order = Order.query.filter_by(member_id=member_id,
                                      id=order_id,
                                      soft=True).first()
        if not order:
            raise NotFound(msg='指定订单不存在')

        mina_config = current_app.config['WE_CHAT']
        notify_url = current_app.config['SITE_DOMAIN'] + mina_config[
            'PAY_NOTIFY_URL']

        wx_helper = WxHelper(merchant_key=mina_config['PAY_KEY'])

        pay_data = {
            'appid': mina_config['APP_ID'],
            'mch_id': mina_config['MCH_ID'],
            'nonce_str': wx_helper.get_random_str(),
            'body': 'snack',
            'out_trade_no': order.order_no,
            'total_fee': int(order.total_price * 100),
            'notify_url': notify_url,
            'trade_type': 'JSAPI',
            'openid': openid
        }
        pay_info = wx_helper.get_pay_info(pay_data)
        if pay_info:
            # 保存prepay_id为了后面发模板消息
            order.update(prepay_id=pay_info['prepay_id'], commit=True)
        else:
            raise WxPayException()
        return pay_info
Example #10
0
 def remove_book(cls, bid):
     book = cls.query.filter_by(id=bid).first()
     if book is None:
         raise NotFound(msg='没有找到相关书籍')
     # 删除图书,软删除
     book.delete(commit=True)
     return True
Example #11
0
def update_group(gid):
    form = UpdateGroup().validate_for_api()
    exists = manager.group_model.get(id=gid)
    if not exists:
        raise NotFound(msg='分组不存在,更新失败')
    exists.update(name=form.name.data, info=form.info.data, commit=True)
    return Success(msg='更新分组成功')
Example #12
0
def user_auth_by_group():
    form = UserGroupAuthForm().validate_for_api()
    user_groups = manager.group_model.get(one=False)
    if user_groups is None:
        raise NotFound(msg='不存在任何用户组')

    for user_group in user_groups:
        users = manager.user_model.query.filter().filter_by(group_id=user_group.id).all()
        if users:
            for user in users:
                # 如果传入权限分组和权限类型则返回对应用户是否获取到授权
                if form.authId.data:
                    # 查询权限表看当前循环用户是否有权限
                    auth = UserAuth.get_user_auth(user.id, form.authId.data, form.authType.data)
                    if auth:
                        setattr(user, 'permission', True)
                        user._fields.append('permission')
                    else:
                        setattr(user, 'permission', False)
                        user._fields.append('permission')
                else:
                    setattr(user, 'permission', False)
                    user._fields.append('permission')
                user.hide('active', 'admin', 'group_id', 'update_time', 'create_time')
            setattr(user_group, 'users', users)
            user_group._fields.append('users')

    return jsonify(user_groups)
Example #13
0
def get_admin_groups():
    start, count = paginate()
    groups = manager.group_model.query.filter().offset(start).limit(
        count).all()
    if groups is None:
        raise NotFound(msg='不存在任何权限组')

    for group in groups:
        auths = db.session.query(manager.auth_model.auth,
                                 manager.auth_model.module).filter_by(
                                     soft=False, group_id=group.id).all()

        auths = [{'auth': auth[0], 'module': auth[1]} for auth in auths]
        res = _split_modules(auths)
        setattr(group, 'auths', res)
        group._fields.append('auths')

    total = get_total_nums(manager.group_model)
    total_page = math.ceil(total / count)
    page = get_page_from_query()

    return json_res(count=count,
                    items=groups,
                    page=page,
                    total=total,
                    total_page=total_page)
Example #14
0
 def address_list(cls, userId):
     address = Address.query.filter_by(userId=userId,
                                       delete_time=None).all()
     if address:
         return address
     else:
         raise NotFound(msg="没有找到相关地址")
Example #15
0
 def get_paginate(cls,
                  member_id,
                  start=0,
                  count=10,
                  order_status=None,
                  soft=True,
                  *,
                  throw=False):
     statement = cls.query.filter_by(soft=soft, member_id=member_id)
     if order_status is not None:
         order_status = cls.validate_order_status(order_status)
         statement = statement.filter_by(order_status=order_status)
     total = statement.count()
     models = statement.order_by(
         cls.id.desc()).offset(start).limit(count).all()
     if not models:
         if not throw:
             return []
         else:
             raise NotFound(msg='还没有相关订单')
     return {
         'start': start,
         'count': count,
         'models': models,
         'total': total
     }
Example #16
0
 def get_paginate_models_with_img(cls,
                                  start,
                                  count,
                                  q=None,
                                  *,
                                  err_msg=None):
     """分页查询带图片资源的多个模型数据(支持搜索)"""
     statement = db.session.query(cls, File.path,
                                  File.id).filter(cls.img_id == File.id,
                                                  cls.delete_time == None)
     if q:
         search_key = '%{}%'.format(q)
         statement = statement.filter(cls.title.ilike(search_key))
     total = statement.count()
     res = statement.order_by(
         cls.id.desc()).offset(start).limit(count).all()
     if not res:
         if err_msg is None:
             return []
         else:
             raise NotFound(msg=err_msg)
     models = cls._add_img_to_models(res)
     return {
         'start': start,
         'count': count,
         'total': total,
         'models': models
     }
Example #17
0
def download_cert():
    form = UserSearchForm().validate_for_api()
    filename = form.openvpn_user_info.data + ".zip"
    directory = os.path.abspath('/opt/vpnuser/')
    if os.path.isdir(directory):
        response = make_response(send_from_directory(directory, filename, as_attachment=True))
        print("response: ", response)
        response.headers['Access-Control-Allow-Origin'] = '*'
        response.headers['Access-Control-Allow-Methods'] = 'GET'
        response.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type'
        response.headers["Content-Disposition"] = "attachment; filename={}".format(filename.encode().decode('latin-1'))
        print("response_headers: ", response.headers)
        if not response:
            return NotFound(msg='File does not exist')
        return response
    return NotFound(msg='Directory does not exist')
Example #18
0
def get_admin_groups():
    start, count = paginate()
    groups = (manager.group_model.query.filter(
        manager.group_model.level != GroupLevelEnum.ROOT.value).offset(
            start).limit(count).all())
    if groups is None:
        raise NotFound("不存在任何分组")

    for group in groups:
        permissions = manager.permission_model.select_by_group_id(group.id)
        setattr(group, "permissions", permissions)
        group._fields.append("permissions")

    # root分组隐藏不显示
    total = (db.session.query(func.count(manager.group_model.id)).filter(
        manager.group_model.level != GroupLevelEnum.ROOT.value,
        manager.group_model.delete_time == None,
    ).scalar())
    total_page = math.ceil(total / count)
    page = get_page_from_query()

    return {
        "count": count,
        "items": groups,
        "page": page,
        "total": total,
        "total_page": total_page,
    }
Example #19
0
 def get_paginate_models_with_img(cls,
                                  start,
                                  count,
                                  q=None,
                                  soft=True,
                                  *,
                                  throw=False):
     """分页查询带图片资源的多个模型数据(支持搜索)"""
     statement = db.session.query(cls, File.path).filter(
         cls.img_id == File.id, ).filter_by(soft=soft)
     if q:
         q = '%{}%'.format(q)
         statement = statement.filter(cls.name.ilike(q))
     total = statement.count()
     res = statement.order_by(
         cls.id.desc()).offset(start).limit(count).all()
     if not res:
         if not throw:
             return []
         else:
             raise NotFound(msg='相关资源未添加或已隐藏')
     models = cls._add_img_to_models(res)
     return {
         'start': start,
         'count': count,
         'total': total,
         'models': models
     }
Example #20
0
def delete_book(id):
    book = Book.query.filter_by(id=id).first()  # 通过Book模型在数据库中查询id=`id`的书籍
    if book is None:
        raise NotFound(msg='没有找到相关书籍')  # 如果书籍不存在,返回一个异常给前端
    # 删除图书,软删除
    book.delete(commit=True)
    return Success(msg='删除图书成功')
Example #21
0
 def remove_group(cls, bid):
     # 分组下有内容不可删除
     group = cls.query.filter_by(id=bid).first()
     if group is None:
         raise NotFound(msg='没有找到相关分组')
     group.delete(commit=True)
     return True
Example #22
0
    def remove_cart(cls, id):

        cart = ShoppingCart.query.filter_by(id=id, delete_time=None).first()
        if cart:
            cart.delete(commit=True)
        else:
            raise NotFound(msg="没有找到相关商品")
Example #23
0
    def get_paginate_models_with_img_voice(cls,
                                           start,
                                           count,
                                           q=None,
                                           *,
                                           err_msg=None):
        """分页查询音乐模型带图片和音乐URL"""
        Image = aliased(File)
        Voice = aliased(File)
        statement = db.session.query(cls, Image.path, Image.id, Voice.path,
                                     Voice.id).filter(cls.img_id == Image.id,
                                                      cls.voice_id == Voice.id,
                                                      cls.delete_time == None)
        if q:
            search_key = '%{}%'.format(q)
            statement = statement.filter(cls.title.ilike(search_key))
        total = statement.count()
        res = statement.order_by(
            cls.id.desc()).offset(start).limit(count).all()
        if not res:
            if err_msg is None:
                return None
            else:
                raise NotFound(msg=err_msg)

        models = cls._add_img_voice_to_models(res)
        return {
            'start': start,
            'count': count,
            'total': total,
            'models': models
        }
Example #24
0
def change_user_password(id):
    form = ResetPasswordForm().validate_for_api()
    user = find_user(id=id)
    if user is None:
        raise NotFound(msg='用户不存在')
    with db.auto_commit():
        user.reset_password(form.new_password.data)
    return Success(msg='密码修改成功')
Example #25
0
 def get_by_order_id(cls, order_id, soft=True, *, throw=False):
     models = cls.query.filter_by(soft=soft, order_id=order_id).all()
     if not models:
         if not throw:
             return []
         else:
             raise NotFound(msg='相关订单商品关系不存在')
     return models
Example #26
0
def delete_user(uid):
    user = manager.user_model.get(id=uid)
    if user is None:
        raise NotFound(msg='用户不存在')
    # user.delete(commit=True)
    # 此处我们使用硬删除,一般情况下,推荐使用软删除即,上一行注释的代码
    user.hard_delete(commit=True)
    return Success(msg='操作成功')
Example #27
0
def refresh():
    identity = get_jwt_identity()
    if identity:
        access_token = create_access_token(identity=identity)
        return jsonify({
            'access_token': access_token
        })
    return NotFound(msg='refresh_token未被识别')
Example #28
0
 def get_by_date(cls, date, *, throw=False):
     model = cls.query.filter_by(soft=True, date=date).first()
     if not model:
         if not throw:
             return None
         else:
             raise NotFound(msg=f'{date}统计数据不存在')
     return model
Example #29
0
 def delivery(self, member_id, order_id):
     order = Order.query.filter_by(
         soft=True, member_id=member_id, id=order_id).filter(
             Order.order_status == OrderStatus.UNDELIVERED.value).first()
     if not order:
         raise NotFound(msg='订单不是待发货状态')
     order.update(order_status=OrderStatus.UNRECEIPTED.value, commit=True)
     return True
Example #30
0
 def check_product_exist(self, product_id):
     product_exist = list(
         filter(lambda x: x.id == product_id, self.o_products))
     if product_exist:
         product = product_exist[0]
     else:
         raise NotFound(msg='id为{}的商品不存在,订单创建失败'.format(product_id))
     return product