Example #1
0
def register(json: UserRegisterSchema):
    """
    注册新用户
    """
    if manager.user_model.count_by_username(g.username) > 0:
        raise Duplicated("用户名重复,请重新输入")  # type: ignore
    if g.email and g.email.strip() != "":
        if manager.user_model.count_by_email(g.email) > 0:
            raise Duplicated("注册邮箱重复,请重新输入")  # type: ignore
    # create a user
    with db.auto_commit():
        user = manager.user_model()
        user.username = g.username
        if g.email and g.email.strip() != "":
            user.email = g.email
        db.session.add(user)
        db.session.flush()
        user.password = g.password
        group_ids = g.group_ids
        # 如果没传分组数据,则将其设定为 guest 分组
        if len(group_ids) == 0:
            from lin import GroupLevelEnum

            group_ids = [GroupLevelEnum.GUEST.value]
        for group_id in group_ids:
            user_group = manager.user_group_model()
            user_group.user_id = user.id
            user_group.group_id = group_id
            db.session.add(user_group)

    return Success("用户创建成功")  # type: ignore
Example #2
0
 def reject_drift(cls, uid=None, did=None):
     with db.auto_commit():
         drift = Drift.query.filter_by(id=did, gifter_id=uid, soft=True).first()
         drift.pending = PendingStatus.Reject
         if drift.address:
             requester = Consumer.get_consumer(drift.requester_id)
             requester.beans += 1
Example #3
0
def init_banner_status():
    """初始化轮播图状态"""
    banner_status = BannerStatus.query.filter_by(delete_time=None).first()
    if banner_status is None:
        with db.auto_commit():
            banner_status = BannerStatus()
            db.session.add(banner_status)
Example #4
0
def update():
    uid = g.user.id
    wx_nickname = request.json['nickname']
    consumer = Consumer.query.get_or_404(uid)
    with db.auto_commit():
        consumer.wx_name = wx_nickname
    return Success()
Example #5
0
def fake():
    with db.auto_commit():
        # 添加书籍
        book1 = Book()
        book1.title = "深入理解计算机系统"
        book1.author = "Randal E.Bryant"
        book1.summary = """
        从程序员的视角,看计算机系统!\n
        本书适用于那些想要写出更快、更可靠程序的程序员。
        通过掌握程序是如何映射到系统上,以及程序是如何执行的,读者能够更好的理解程序的行为为什么是这样的,以及效率低下是如何造成的。
        粗略来看,计算机系统包括处理器和存储器硬件、编译器、操作系统和网络互连环境。
        而通过程序员的视角,读者可以清晰地明白学习计算机系统的内部工作原理会对他们今后作为计算机科学研究者和工程师的工作有进一步的帮助。
        它还有助于为进一步学习计算机体系结构、操作系统、编译器和网络互连做好准备。\n
        本书的主要论题包括:数据表示、C程序的机器级表示、处理器结构,程序优化、存储器层次结构、链接、异常控制流、虚拟存储器和存储器管理、系统级I/O、网络编程和并发编程。书中所覆盖的内容主要是这些方面是如何影响应用和系统程序员的。
        """
        book1.image = "https://img3.doubanio.com/lpic/s1470003.jpg"
        db.session.add(book1)

        book2 = Book()
        book2.title = "C程序设计语言"
        book2.author = "(美)Brian W. Kernighan"
        book2.summary = """
        在计算机发展的历史上,没有哪一种程序设计语言像C语言这样应用广泛。
        本书原著即为C语言的设计者之一Dennis M.Ritchie和著名计算机科学家Brian W.Kernighan合著的一本介绍C语言的权威经典著作。
        我们现在见到的大量论述C语言程序设计的教材和专著均以此书为蓝本。
        原著第1版中介绍的C语言成为后来广泛使用的C语言版本——标准C的基础。
        人们熟知的“hello,World"程序就是由本书首次引入的,现在,这一程序已经成为众多程序设计语言入门的第一课。\n
        原著第2版根据1987年制定的ANSIC标准做了适当的修订.引入了最新的语言形式,并增加了新的示例,通过简洁的描述、典型的示例,作者全面、系统、准确地讲述了C语言的各个特性以及程序设计的基本方法。
        对于计算机从业人员来说,《C程序设计语言》是一本必读的程序设计语 言方面的参考书。
        """
        book2.image = "https://img3.doubanio.com/lpic/s1106934.jpg"
        db.session.add(book2)
Example #6
0
def create_group_file():
    form = CreateGroupFile().validate_for_api()
    print(form.type.data, 'form.type.data')
    FileManage = FileMap[form.type.data]
    # 1 img ,2 txt,3 audio,4 video
    current_path = current_app.static_url_path
    site_domain = current_app.config.get('SITE_DOMAIN') \
        if current_app.config.get('SITE_DOMAIN') else 'http://127.0.0.1:2100'
    replace_path = site_domain + current_path
    current_user = get_current_user()
    with db.auto_commit():
        for item in form.paths.data:
            # real_path=item.path.replace(replace_path,'')
            real_path = item['path'].replace(replace_path, '')
            one = FileManage.query.filter_by(
                path=real_path, folder_id=form.folder_id.data).first()
            if not one:
                File.query.filter_by(path=real_path).update(
                    {File.active: 1}, synchronize_session=False)
                FileManage.create(folder_id=form.folder_id.data,
                                  path=real_path,
                                  title=item['title'],
                                  auth_id=current_user.id)

    return Success(msg='添加成功')
Example #7
0
def update_user(uid: int, json: UpdateUserInfoSchema):
    """
    更新用户信息
    """
    user = manager.user_model.get(id=uid)
    if user is None:
        raise NotFound("用户不存在")
    if user.email != g.email:
        exists = manager.user_model.get(email=g.email)
        if exists:
            raise ParameterError("邮箱已被注册,请重新输入邮箱")
    with db.auto_commit():
        user.email = g.email
        group_ids = g.group_ids
        # 清空原来的所有关联关系
        manager.user_group_model.query.filter_by(user_id=user.id).delete(
            synchronize_session=False)
        # 根据传入分组ids 新增关联记录
        user_group_list = list()
        # 如果没传分组数据,则将其设定为 guest 分组
        if not group_ids:
            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 #8
0
def init(force=False):
    db.create_all()
    if force:
        db.drop_all()
        db.create_all()
    elif (manager.user_model.get(one=False)
          or manager.user_group_model.get(one=False)
          or manager.group_model.get(one=False)):
        exit("表中存在数据,初始化失败")
    with db.auto_commit():
        # 创建一个超级管理员分组
        root_group = manager.group_model()
        root_group.name = "Root"
        root_group.info = "超级用户组"
        root_group.level = GroupLevelEnum.ROOT.value
        db.session.add(root_group)
        # 创建一个超级管理员
        root = manager.user_model()
        root.username = "******"
        db.session.add(root)
        db.session.flush()
        root.password = "******"
        # root用户 and  超级管理员分组 对应关系写入user_group表中
        user_group = manager.user_group_model()
        user_group.user_id = root.id
        user_group.group_id = root_group.id
        db.session.add(user_group)
        # 添加 默认游客组
        guest_group = manager.group_model()
        guest_group.name = "Guest"
        guest_group.info = "游客组"
        guest_group.level = GroupLevelEnum.GUEST.value
        db.session.add(guest_group)
        # 初始化权限
        manager.sync_permissions()
Example #9
0
 def create_banner(cls, data):
     """创建一个轮播图"""
     data = dict_rm_none(data)
     with db.auto_commit():
         banner = Banner()
         banner.set_attrs(data)
         db.session.add(banner)
     return True
Example #10
0
 def place(self):
     if not self.mid or not self.products:
         raise Failed(msg='缺少会员ID和商品参数, 下单失败')
     with db.auto_commit():
         self.o_products = self._get_o_products()
         order_snap = self._snap_order()
         res = self._create_order(order_snap)
     return res
Example #11
0
def recover_group_file():
    form = DeleteOrRecoverGroupFile().validate_for_api()
    # 1 img ,2 txt,3 audio,4 video
    FileManage = FileMap[form.type.data]
    with db.auto_commit():
        FileManage.query.filter(FileManage.id.in_(form.ids.data), ).update(
            {FileManage.delete_time: None}, synchronize_session=False)
    return Success(msg='文件已恢复')
Example #12
0
def set_value_by_key(key, value, expires_at, des):
    """通过 key 设置暂存数据表中的值"""
    obj_staging = Staging.query.filter_by(key=key).first()
    # 若暂存区已存在此参数则进行更新
    if obj_staging:
        with db.auto_commit():
            obj_staging.value = value
            if expires_at:
                obj_staging.expires_at = expires_at
    # 若暂存区不存在此参数则新建
    else:
        with db.auto_commit():
            obj_staging = Staging()
            obj_staging.key = key
            obj_staging.value = value
            obj_staging.expires_at = expires_at
            obj_staging.des = des
            db.session.add(obj_staging)
Example #13
0
def put_events():
    form = EventsForm().validate_for_api()
    event = Event.query.filter_by(group_id=form.group_id.data,
                                  soft=False).first()
    if event is None:
        raise NotFound(msg='当前权限组不存在推送项')
    with db.auto_commit():
        event.message_events = ','.join(form.events.data)
    return Success(msg='更新成功')
Example #14
0
 def __new_books_from_api(cls, data):
     """将网上数据添加到数据库"""
     with db.auto_commit():
         for book_dict in data:
             book = Book()
             book.set_attrs(book_dict)
             if hasattr(book, 'summary'):
                 book.summary = cls.handle_new_line(book.summary)
             db.session.add(book)
Example #15
0
def change_user_password(uid):
    form = ResetPasswordForm().validate_for_api()

    user = find_user(id=uid)
    if user is None:
        raise NotFound(msg='用户不存在')
    with db.auto_commit():
        user.reset_password(form.new_password.data)

    return Success(msg='密码修改成功')
Example #16
0
def remove_auths():
    form = RemoveAuths().validate_for_api()

    with db.auto_commit():
        db.session.query(manager.auth_model).filter(
            manager.auth_model.auth.in_(form.auths.data),
            manager.auth_model.group_id == form.group_id.data).delete(
                synchronize_session=False)

    return Success(msg='删除权限成功')
Example #17
0
 def __save_consumer(cls, openid):
     with db.auto_commit():
         consumer = Consumer.query.filter_by(wx_open_id=openid,
                                             soft=True).first()
         if consumer is None:
             consumer = Consumer()
             consumer.wx_open_id = openid
             db.session.add(consumer)
             db.session.flush()
         return consumer
Example #18
0
def create_events():
    form = EventsForm().validate_for_api()
    event = Event.query.filter_by(group_id=form.group_id.data,
                                  soft=False).first()
    if event:
        raise Forbidden(msg='当前权限组已存在推送项')
    with db.auto_commit():
        ev = Event()
        ev.group_id = form.group_id.data
        ev.message_events = ','.join(form.events.data)
    return Success(msg='创建成功')
Example #19
0
 def register_by_mina(wx_open_id):
     user = manager.user_model.query.filter_by(wx_open_id=wx_open_id).first()
     if user:
         raise Forbidden(msg='openid has been registered')
     else:
         with db.auto_commit():
             user = manager.user_model()
             user.wx_open_id = wx_open_id
             user.username = '******' + str(manager.user_model.query.count())
             db.session.add(user)
         return Success()
Example #20
0
def delete_group_file():
    form = DeleteOrRecoverGroupFile().validate_for_api()
    isClear = int(form.isClear.data)
    FileManage = FileMap[form.type.data]
    # 1 img ,2 txt,3 audio,4 video,删除文件
    if (isClear):
        fileList = FileManage.query.filter(FileManage.id.in_(
            form.ids.data), ).all()
        with db.auto_commit():
            for i in fileList:
                i.hard_delete()
                # file_path=_store_dir+i.path
                # if os.path.exists(file_path):
                #     os.remove(file_path)
    else:
        with db.auto_commit():
            FileManage.query.filter(FileManage.id.in_(form.ids.data), ).update(
                {FileManage.delete_time: datetime.now()},
                synchronize_session=False)
    return Success(msg='回收站已清空' if isClear else '删除成功')
Example #21
0
def remove_auths(json: GroupIdWithPermissionIdListSchema):
    """
    删除多个权限
    """

    with db.auto_commit():
        db.session.query(manager.group_permission_model).filter(
            manager.group_permission_model.permission_id.in_(g.permission_ids),
            manager.group_permission_model.group_id == g.group_id,
        ).delete(synchronize_session=False)

    return Success("删除权限成功")
Example #22
0
def update_book(id):
    form = CreateOrUpdateBookForm().validate_for_api()  # 校验参数
    book = Book.query.filter_by(id=id).first()  # 通过Book模型在数据库中查询id=`id`的书籍
    if book is None:
        raise NotFound(msg='没有找到相关书籍')  # 如果书籍不存在,返回一个异常给前端
    # 更新图书
    with db.auto_commit():
        book.title = form.title.data
        book.author = form.author.data
        book.summary = form.summary.data
        book.image = form.image.data
    return Success(msg='更新图书成功')
Example #23
0
def update(pid):
    form = ProductContent().validate_for_api()
    props = validate_product_props()
    with db.auto_commit():
        Product.edit_model(pid, form.data, commit=False, throw=True)
        if props:
            ProductProperty.edit_properties(pid, props)
        if form.theme_ids.data:
            ThemeProduct.edit_themes(form.theme_ids.data, pid)
        if form.desc_img_ids.data:
            ProductImage.edit_imgs_for_product(pid, form.desc_img_ids.data)
    return Success('商品更新成功')
Example #24
0
def dispatch_auths():
    form = DispatchAuths().validate_for_api()
    with db.auto_commit():
        for auth in form.auths.data:
            one = manager.auth_model.get(group_id=form.group_id.data,
                                         auth=auth)
            if not one:
                meta = find_auth_module(auth)
                manager.auth_model.create(group_id=form.group_id.data,
                                          auth=meta.auth,
                                          module=meta.module)
    return Success(msg='添加权限成功')
Example #25
0
 def collect_or_not_quota(self, quota):
     """收藏/取消收藏语录"""
     with db.auto_commit():
         # 如果已收藏
         if quota in self.collected_quotas:
             self.collected_quotas.remove(quota)
             is_collect = False
         # 未收藏
         else:
             self.collected_quotas.append(quota)
             is_collect = True
     return is_collect
Example #26
0
 def like_or_not_quota(self, quota):
     """点赞/取消点赞语录"""
     with db.auto_commit():
         # 如果已点赞
         if quota in self.liked_quotas:
             self.liked_quotas.remove(quota)
             is_like = False
         # 未点赞
         else:
             self.liked_quotas.append(quota)
             is_like = True
     return is_like
Example #27
0
def change_user_password(uid: int, json: ResetPasswordSchema):
    """
    修改用户密码
    """

    user = manager.find_user(id=uid)
    if not user:
        raise NotFound("用户不存在")

    with db.auto_commit():
        user.reset_password(g.new_password)

    return Success("密码修改成功")
Example #28
0
    def mail_drift(cls, uid=None, did=None):
        with db.auto_commit():
            drift = Drift.query.filter_by(id=did, gifter_id=uid, soft=True).first()
            drift.pending = PendingStatus.Success

            wished = Wish.query.filter_by(uid=drift.requester_id, bid=drift.bid, launched=False, soft=True).first()
            if wished:
                wished.launched = True
            requester = Consumer.get_consumer(drift.requester_id)
            requester.update_receive_counter()

            gifted = Gift.query.filter_by(uid=drift.gifter_id, bid=drift.bid, launched=False, soft=True).first()
            gifted.consumer.update_send_counter()
            gifted.launched = True
Example #29
0
def update_user(uid):
    form = UpdateUserInfoForm().validate_for_api()

    user = manager.user_model.get(id=uid)
    if user is None:
        raise NotFound(msg='用户不存在')
    if user.email != form.email.data:
        exists = manager.user_model.get(email=form.email.data)
        if exists:
            raise ParameterException(msg='邮箱已被注册,请重新输入邮箱')
    with db.auto_commit():
        user.email = form.email.data
        user.group_id = form.group_id.data
    return Success(msg='操作成功')
Example #30
0
def dispatch_auths(json: GroupIdWithPermissionIdListSchema):
    """
    分配多个权限
    """
    with db.auto_commit():
        for permission_id in g.permission_ids:
            one = manager.group_permission_model.get(
                group_id=g.group_id, permission_id=permission_id)
            if not one:
                manager.group_permission_model.create(
                    group_id=g.group_id,
                    permission_id=permission_id,
                )
    return Success("添加权限成功")