Пример #1
0
    def UpdateRoute():
        """
        更新文档 (DB)
        会更新文档分组和文件名
        """
        try:
            req_id = int(request.form['id'])
            req_filename = request.form['filename']
            req_docClass = int(request.form['doc_class_id'])
            if not req_filename or not (FileUtil.is_document(req_filename)
                                        or FileUtil.is_image(req_filename)):
                raise ParamError(ParamType.FORM)
        except:
            raise ParamError(ParamType.FORM)
        req_doc = Document(did=req_id,
                           filename=req_filename,
                           docClass=req_docClass)

        filepath = f'{Config.UPLOAD_DOC_FOLDER}/{g.user}/'
        status, new_document = DocumentDao().updateDocument(uid=g.user,
                                                            document=req_doc)
        if status == DbStatusType.NOT_FOUND or not new_document or not os.path.exists(
                filepath + new_document.uuid):
            return Result.error(ResultCode.NOT_FOUND).setMessage(
                "Document Not Found").json_ret()
        elif status == DbStatusType.FAILED:
            return Result.error(ResultCode.DATABASE_FAILED).setMessage(
                "Document Update Failed").json_ret()
        else:  # Success
            return Result.ok().setData(new_document.to_json()).json_ret()
Пример #2
0
    def UpdateRoute():
        """ 更新 """
        try:
            req_id = int(request.form['id'])
            req_title = request.form['title']
            req_content = request.form['content']
            req_group_id = int(request.form['group_id'])
        except:
            raise ParamError(ParamType.FORM)
        if not (Config.FMT_NOTE_TITLE_MIN <= len(req_title) <=
                Config.FMT_NOTE_TITLE_MAX):
            return Result().error(
                ResultCode.BAD_REQUEST).setMessage('Format Error').json_ret()
        req_note = Note(nid=req_id,
                        title=req_title,
                        content=req_content,
                        group=req_group_id)

        status, new_note = NoteDao().updateNote(uid=g.user, note=req_note)
        if status == DbStatusType.NOT_FOUND:
            return Result.error(
                ResultCode.NOT_FOUND).setMessage("Note Not Found").json_ret()
        elif status == DbStatusType.FAILED or not new_note:
            return Result.error(ResultCode.DATABASE_FAILED).setMessage(
                "Note Update Failed").json_ret()
        else:  # Success
            return Result.ok().setData(new_note.to_json()).json_ret()
Пример #3
0
    def InsertRoute():
        """ 插入 """
        try:
            req_title = request.form['title']
            req_content = request.form['content']
            req_group_id = int(request.form['group_id'])
            req_ct = request.form['create_time']
            req_ut = request.form['update_time']
        except:
            raise ParamError(ParamType.FORM)
        if not (Config.FMT_NOTE_TITLE_MIN <= len(req_title) <=
                Config.FMT_NOTE_TITLE_MAX):
            return Result().error(
                ResultCode.BAD_REQUEST).setMessage('Format Error').json_ret()
        req_note = Note(nid=-1,
                        title=req_title,
                        content=req_content,
                        group=req_group_id,
                        create_time=req_ct,
                        update_time=req_ut)

        status, new_note = NoteDao().insertNote(uid=g.user, note=req_note)
        if status == DbStatusType.FOUNDED:
            return Result.error(
                ResultCode.HAS_EXISTED).setMessage("Note Existed").json_ret()
        elif status == DbStatusType.FAILED or not new_note:
            return Result.error(ResultCode.DATABASE_FAILED).setMessage(
                "Note Insert Failed").json_ret()
        else:  # Success
            return Result.ok().setData(new_note.to_json()).json_ret()
Пример #4
0
    def UpdateRoute():
        """ 更新 """
        try:
            req_id = int(request.form['id'])
            req_name = request.form['name']
            req_order = int(request.form['order'])
            req_color = request.form['color']
        except:
            raise ParamError(ParamType.FORM)
        if not (Config.FMT_GROUP_NAME_MIN <= len(req_name) <=
                Config.FMT_GROUP_NAME_MAX):
            return Result().error(
                ResultCode.BAD_REQUEST).setMessage('Format Error').json_ret()
        req_group = Group(gid=req_id,
                          name=req_name,
                          order=req_order,
                          color=req_color)

        status, new_group = GroupDao().updateGroup(uid=g.user, group=req_group)
        if status == DbStatusType.NOT_FOUND:
            return Result.error(
                ResultCode.NOT_FOUND).setMessage("Group Not Found").json_ret()
        elif status == DbStatusType.DUPLICATE:
            return Result.error(ResultCode.DUPLICATE_FAILED).setMessage(
                "Group Name Duplicate").json_ret()
        elif status == DbStatusType.DEFAULT:
            return Result.error(ResultCode.DEFAULT_FAILED).setMessage(
                "Could Not Update Default Group").json_ret()
        elif status == DbStatusType.FAILED or not new_group:
            return Result.error(ResultCode.DATABASE_FAILED).setMessage(
                "Group Update Failed").json_ret()
        else:  # Success
            return Result.ok().setData(new_group.to_json()).json_ret()
Пример #5
0
    def LoginRoute():
        """ 登录 """
        try:
            username = request.form['username']  # 必须
            password = request.form['password']  # 必须
            ex = request.form.get('expiration')  # 可选
            if not ex or ex == '0':
                ex = Config.LOGIN_TOKEN_EX
        except:
            raise ParamError(ParamType.FORM)

        try:
            ex = int(ex)
        except ValueError:
            raise ParamError(ParamType.FORM)

        status, user = UserDao().checkUserPassword(username, password)
        if status == DbStatusType.FAILED:
            return Result.error(ResultCode.UNAUTHORIZED).setMessage(
                "Password Error").json_ret()
        elif status == DbStatusType.NOT_FOUND:
            return Result.error(ResultCode.UNAUTHORIZED).setMessage(
                "User Not Found").json_ret()
        else:  # Success
            token = AuthUtil.generate_token(user.id, ex)
            if not UserTokenDao().addToken(user.id, token):  # Add to redis
                return Result.error(ResultCode.UNAUTHORIZED).setMessage(
                    "Login Failed").json_ret()

            return Result.ok().setData(user.to_json()).putData(
                'token',
                token).json_ret(headers={'Authorization': 'Bearer ' + token})
Пример #6
0
    def InsertRoute():
        """ 插入 """
        try:
            req_name = request.form['name']
            req_color = request.form.get('color')
        except:
            raise ParamError(ParamType.FORM)
        if not (Config.FMT_GROUP_NAME_MIN <= len(req_name) <=
                Config.FMT_GROUP_NAME_MAX):
            return Result().error(
                ResultCode.BAD_REQUEST).setMessage('Format Error').json_ret()
        req_group = Group(gid=-1, name=req_name, color=req_color)

        status, new_group = GroupDao().insertGroup(uid=g.user, group=req_group)
        if status == DbStatusType.FOUNDED:
            return Result.error(
                ResultCode.HAS_EXISTED).setMessage("Group Existed").json_ret()
        elif status == DbStatusType.DUPLICATE:
            return Result.error(ResultCode.DUPLICATE_FAILED).setMessage(
                "Group Name Duplicate").json_ret()
        elif status == DbStatusType.FAILED or not new_group:
            return Result.error(ResultCode.DATABASE_FAILED).setMessage(
                "Group Insert Failed").json_ret()
        else:  # Success
            return Result.ok().setData(new_group.to_json()).json_ret()
Пример #7
0
    def RegisterRoute():
        """ 注册 """
        try:
            username = request.form['username']  # 必须
            password = request.form['password']  # 必须
        except:
            raise ParamError(ParamType.FORM)

        # Format
        if not (Config.FMT_USERNAME_MIN <= len(username) <=
                Config.FMT_USERNAME_MAX and Config.FMT_PASSWORD_MIN <=
                len(password) <= Config.FMT_PASSWORD_MAX):
            return Result.error(
                ResultCode.BAD_REQUEST).setMessage('Format Error').json_ret()

        # Database
        status, new_user = UserDao().insertUser(username, password)
        if status == DbStatusType.FAILED:
            return Result.error(ResultCode.DATABASE_FAILED).setMessage(
                "Register Failed").json_ret()
        elif status == DbStatusType.FOUNDED:
            return Result.error(
                ResultCode.HAS_EXISTED).setMessage("User Existed").json_ret()
        else:  # Success
            return Result.ok().setData(new_user.to_json()).json_ret()
Пример #8
0
    def InsertRoute():
        """ 插入 """
        try:
            req_title = request.form['title']
            req_url = request.form['url']
            req_content = request.form['content']

            if len(req_title) > Config.FMT_STAR_TITLE_MAX:
                req_title = req_title[:Config.FMT_STAR_TITLE_MAX - 3] + '...'
            if len(req_content) > Config.FMT_STAR_CONTENT_MAX:
                req_content = req_content[:Config.FMT_STAR_CONTENT_MAX -
                                          3] + '...'
        except:
            raise ParamError(ParamType.FORM)
        req_star = StarItem(sid=-1,
                            title=req_title,
                            url=req_url,
                            content=req_content)

        status, new_star = StarDao().insertStar(uid=g.user, star=req_star)
        if status == DbStatusType.FOUNDED:
            return Result.error(ResultCode.HAS_EXISTED).setMessage(
                "StarItem Existed").json_ret()
        elif status == DbStatusType.DUPLICATE:
            return Result.error(ResultCode.DATABASE_FAILED).setMessage(
                "StatItem Insert Failed").json_ret()
        else:  # Success
            return Result.ok().setData(new_star.to_json()).json_ret()
Пример #9
0
 def DeleteRoute():
     """ 删除 课程表 """
     status, schedule, week = ScheduleDao().deleteSchedule(uid=g.user)
     if status == DbStatusType.NOT_FOUND:
         return Result.error(ResultCode.NOT_FOUND).setMessage(
             'Schedule Not Found').json_ret()
     elif status == DbStatusType.FAILED:
         return Result.error(ResultCode.DATABASE_FAILED).setMessage(
             'Delete Schedule Failed').json_ret()
     else:
         return Result.ok().putData('schedule',
                                    schedule).putData('week',
                                                      week).json_ret()
Пример #10
0
    def DeleteRoute(cid: int):
        """ 删除文件分组 """
        docclass = DocClassDao().queryDocClassByIdOrName(uid=g.user, cid_name=int(cid))
        isToDefault: bool = request.args.get('default', 'false').lower() == 'true'

        status = DocClassDao().deleteDocClass(uid=g.user, cid=cid, toDefault=isToDefault)
        if status == DbStatusType.NOT_FOUND or not docclass:
            return Result.error(ResultCode.NOT_FOUND).setMessage("Document Class Not Found").json_ret()
        elif status == DbStatusType.DEFAULT:
            return Result.error(ResultCode.DEFAULT_FAILED).setMessage("Could Not Delete Default Document Class").json_ret()
        elif status == DbStatusType.FAILED:
            return Result.error(ResultCode.DATABASE_FAILED).setMessage("Document Class Delete Failed").json_ret()
        else:  # Success
            return Result.ok().setData(docclass.to_json()).json_ret()
Пример #11
0
 def DeleteRoute(did: int):
     """ 删除文档 (DB + FS) """
     document: Document = DocumentDao().queryDocumentById(uid=g.user,
                                                          did=did)
     status = DocumentDao().deleteDocument(uid=g.user, did=did)
     if status == DbStatusType.NOT_FOUND or not document:
         return Result.error(ResultCode.NOT_FOUND).setMessage(
             "Document Not Found").json_ret()
     elif status == DbStatusType.FAILED:
         return Result.error(ResultCode.DATABASE_FAILED).setMessage(
             "Document Delete Failed").json_ret()
     else:  # Success
         server_filepath = f'{Config.UPLOAD_DOC_FOLDER}/{g.user}/{document.uuid}'
         if os.path.exists(server_filepath):
             os.remove(server_filepath)
         return Result.ok().setData(document.to_json()).json_ret()
Пример #12
0
    def GetShareCodeContent(sc: str):
        """ 获取分享码内含的内容 """
        try:
            uid = int(sc.split("_")[2])  # biji_sc_1_xxx
        except KeyError:
            raise ParamError(ParamType.ROUTE)
        except ValueError:
            raise ParamError(ParamType.ROUTE)

        dids = ShareCodeDao().getShareContent(sc)
        if len(dids) == 0:
            return Result.error(ResultCode.BAD_REQUEST).setMessage("Share Code Not Exist").json_ret()
        documents = DocumentDao().queryDocumentsByIds(uid, dids)
        if len(documents) == 0:  # 没有文件
            return Result.error(ResultCode.SHARE_DOCUMENT_NULL).setMessage("Share Code Not Include File").json_ret()
        return Result.ok().setData(Document.to_jsons(documents)).json_ret()
Пример #13
0
 def GetByIdRoute(sid: int):
     """ 根据 sid 获取分组 """
     star = StarDao().queryStarByIdOrUrl(uid=g.user, sid_url=sid)
     if not star:
         return Result.error(ResultCode.NOT_FOUND).setMessage(
             "StarItem Not Found").json_ret()
     return Result.ok().setData(star.to_json()).json_ret()
Пример #14
0
 def GetByIdRoute(gid: int):
     """ gid 查询分组 """
     group = GroupDao().queryGroupByIdOrName(uid=g.user, gid_name=int(gid))
     if not group:
         return Result.error(
             ResultCode.NOT_FOUND).setMessage("Group Not Found").json_ret()
     return Result.ok().setData(group.to_json()).json_ret()
Пример #15
0
 def GetByIdRoute(nid: int):
     """ nid 查询笔记 """
     note = NoteDao().queryNoteById(uid=g.user, nid=nid)
     if not note:
         return Result.error(
             ResultCode.NOT_FOUND).setMessage("Note Not Found").json_ret()
     return Result.ok().setData(note.to_json()).json_ret()
Пример #16
0
    def InsertRoute():
        """
        插入文档 (DB + FS)
        先保存文件,记录保存的文件名和 uuid (当前时间)
        然后将文件名 uuid classId 插入数据库,返回
        """
        try:
            upload_file = request.files.get('file')  # 包含文件名
            req_docClass = int(request.form['doc_class_id'])
            if not (upload_file and req_docClass):
                raise ParamError(ParamType.FORM)
        except:
            raise ParamError(ParamType.FORM)

        # # Save
        # file_len = len(upload_file.read())
        # if file_len > Config.MAX_UPLOAD_SIZE:  # 50M
        #     return Result.error(ResultCode.BAD_REQUEST).setMessage('File Out Of Size').json_ret()
        server_filepath = f'{Config.UPLOAD_DOC_FOLDER}/{g.user}/'
        uuid, type_ok, save_ok = FileUtil.saveFile(file=upload_file,
                                                   path=server_filepath,
                                                   file_image=False)
        if not type_ok:  # 格式错误
            return Result.error(ResultCode.BAD_REQUEST).setMessage(
                'File Extension Error').json_ret()
        if not save_ok:  # 保存失败
            return Result.error(ResultCode.SAVE_FILE_FAILED).setMessage(
                'Save Document Failed').json_ret()

        # Database
        document = Document(did=-1,
                            filename=upload_file.filename,
                            uuid=uuid,
                            docClass=req_docClass)
        status, new_document = DocumentDao().insertDocument(uid=g.user,
                                                            document=document)
        if status == DbStatusType.FOUNDED:  # -1 永远不会
            os.remove(os.path.join(server_filepath, uuid))
            return Result.error(ResultCode.HAS_EXISTED).setMessage(
                "Document Existed").json_ret()
        elif status == DbStatusType.FAILED or not new_document:
            os.remove(os.path.join(server_filepath, uuid))
            return Result.error(ResultCode.DATABASE_FAILED).setMessage(
                "Document Insert Failed").json_ret()
        else:  # Success
            return Result.ok().setData(new_document.to_json()).json_ret()
Пример #17
0
 def GetOneRoute(did: int):
     """ did 查询文档 """
     document = DocumentDao().queryDocumentById(uid=g.user, did=did)
     filepath = f'{Config.UPLOAD_DOC_FOLDER}/{g.user}/'
     if not document or not os.path.exists(filepath + document.uuid):
         return Result.error(ResultCode.NOT_FOUND).setMessage(
             "Document Not Found").json_ret()
     return Result.ok().setData(document.to_json()).json_ret()
Пример #18
0
 def LogoutRoute():
     """ 注销 """
     count = UserTokenDao().removeToken(g.user)
     if count == 0:
         return Result.error(ResultCode.DATABASE_FAILED).setMessage(
             "Logout Failed").json_ret()
     else:
         return Result.ok().putData("count", count).json_ret()
Пример #19
0
 def CurrRoute():
     """ 当前登陆用户 """
     user = UserDao().queryUserById(g.user)
     if not user:
         return Result.error(ResultCode.UNAUTHORIZED).setMessage(
             "User Not Found").json_ret()
     else:
         return Result.ok().setData(user.to_json()).json_ret()
Пример #20
0
 def GetRoute():
     """ 获得 课程表 """
     sc, week = ScheduleDao().querySchedule(uid=g.user)
     if not sc:
         return Result.error(ResultCode.NOT_FOUND).setMessage(
             'Schedule Not Found').json_ret()
     else:
         return Result.ok().putData("schedule",
                                    sc).putData("week", week).json_ret()
Пример #21
0
    def InsertRoute():
        """ 新建文件分组 """
        try:
            req_name = request.form['name']
        except:
            raise ParamError(ParamType.FORM)
        if not (Config.FMT_DOCCLASS_NAME_MIN <= len(req_name) <= Config.FMT_DOCCLASS_NAME_MAX):
            return Result().error(ResultCode.BAD_REQUEST).setMessage('Format Error').json_ret()
        req_docclass = DocClass(cid=-1, name=req_name)

        status, new_docClass = DocClassDao().insertDocClass(uid=g.user, docClass=req_docclass)
        if status == DbStatusType.FOUNDED:
            return Result.error(ResultCode.HAS_EXISTED).setMessage("Document Class Existed").json_ret()
        elif status == DbStatusType.DUPLICATE:
            return Result.error(ResultCode.DUPLICATE_FAILED).setMessage("Document Class Name Duplicate").json_ret()
        elif status == DbStatusType.FAILED or not new_docClass:
            return Result.error(ResultCode.DATABASE_FAILED).setMessage("Document Class Insert Failed").json_ret()
        else:  # Success
            return Result.ok().setData(new_docClass.to_json()).json_ret()
Пример #22
0
 def GetAllRoute():
     """ 所有文件分组 / name """
     name = request.args.get('name')
     if name:  # 查詢
         docClass = DocClassDao().queryDocClassByIdOrName(uid=g.user, cid_name=str(name))
         if not docClass:
             return Result.error(ResultCode.NOT_FOUND).setMessage("Document Class Not Found").json_ret()
         return Result.ok().setData(docClass.to_json()).json_ret()
     else:  # 無查詢
         docClasses = DocClassDao().queryAllDocClasses(uid=g.user)
         return Result.ok().setData(DocClass.to_jsons(docClasses)).json_ret()
Пример #23
0
    def DeleteRoute(gid: int):
        """ 删除 """
        group: Group = GroupDao().queryGroupByIdOrName(uid=g.user,
                                                       gid_name=int(gid))
        isToDefault: bool = request.args.get('default',
                                             'false').lower() == 'true'

        status = GroupDao().deleteGroup(uid=g.user,
                                        gid=gid,
                                        toDefault=isToDefault)
        if status == DbStatusType.NOT_FOUND or not group:
            return Result.error(
                ResultCode.NOT_FOUND).setMessage("Group Not Found").json_ret()
        elif status == DbStatusType.DEFAULT:
            return Result.error(ResultCode.DEFAULT_FAILED).setMessage(
                "Could Not Delete Default Group").json_ret()
        elif status == DbStatusType.FAILED:
            return Result.error(ResultCode.DATABASE_FAILED).setMessage(
                "Group Delete Failed").json_ret()
        else:  # Success
            return Result.ok().setData(group.to_json()).json_ret()
Пример #24
0
 def GetAllRoute():
     """ 所有分组 / name """
     name = request.args.get('name')
     if name:  # 有查詢
         group = GroupDao().queryGroupByIdOrName(uid=g.user,
                                                 gid_name=str(name))
         if not group:
             return Result.error(ResultCode.NOT_FOUND).setMessage(
                 "Group Not Found").json_ret()
         return Result.ok().setData(group.to_json()).json_ret()
     else:  # 無查詢
         groups = GroupDao().queryAllGroups(uid=g.user)
         return Result.ok().setData(Group.to_jsons(groups)).json_ret()
Пример #25
0
    def UpdateRoute():
        """ 更新文件分组 """
        try:
            req_id = int(request.form['id'])
            req_name = request.form['name']
        except:
            raise ParamError(ParamType.FORM)
        if not (Config.FMT_DOCCLASS_NAME_MIN <= len(req_name) <= Config.FMT_DOCCLASS_NAME_MAX):
            return Result().error(ResultCode.BAD_REQUEST).setMessage('Format Error').json_ret()
        req_docclass = DocClass(cid=req_id, name=req_name)

        status, new_docclass = DocClassDao().updateDocClass(uid=g.user, docClass=req_docclass)
        if status == DbStatusType.NOT_FOUND:
            return Result.error(ResultCode.NOT_FOUND).setMessage("Document Class Not Found").json_ret()
        elif status == DbStatusType.DUPLICATE:
            return Result.error(ResultCode.DUPLICATE_FAILED).setMessage("Document Class Name Duplicate").json_ret()
        elif status == DbStatusType.DEFAULT:
            return Result.error(ResultCode.DEFAULT_FAILED).setMessage("Could Not Update Default Document Class").json_ret()
        elif status == DbStatusType.FAILED:
            return Result.error(ResultCode.DATABASE_FAILED).setMessage("Document Class Update Failed").json_ret()
        else:  # Success
            return Result.ok().setData(new_docclass.to_json()).json_ret()
Пример #26
0
    def NewShareCodeRoute():
        """ !!!! 新建共享码 addShareCode """
        try:
            req_Ex = int(request.form['ex'])
        except KeyError:
            req_Ex = Config.SHARE_TOKEN_EX
        except ValueError:
            raise ParamError(ParamType.FORM)

        cid = request.args.get('cid')
        if cid:  # 将整个集合共享 /share?cid
            try:
                cid = int(cid)
            except ValueError:
                raise ParamError(ParamType.FORM)
            documents = DocumentDao().queryDocumentsByClassId(g.user, int(cid))
            ids: List[int] = [did.id for did in documents]
        else:  # 文档集合分享 /share
            try:
                req_didList = request.form.getlist('did')
                if len(req_didList) == 0:
                    raise ParamError(ParamType.FORM)
                ids: List[int] = [int(did) for did in req_didList]
            except:
                raise ParamError(ParamType.FORM)
        # ids
        sc, docs = ShareCodeDao().addShareCode(uid=g.user, dids=ids, ex=req_Ex)
        if len(docs) == 0:
            return Result.error(ResultCode.SHARE_DOCUMENT_NULL).setMessage('Share Documents Null').json_ret()
        if sc == '':
            return Result.error(ResultCode.DATABASE_FAILED).setMessage('Document Share Code Generate Failed').json_ret()
        else:
            data = {
                'sc': sc,
                'documents': Document.to_jsons(docs)
            }
            return Result.ok().setData(data).json_ret()
Пример #27
0
    def GetRawDocument(sc: str):
        """ !!!! 通过 共享码 下载 """
        ok, uid, _ = ShareCodeDao.is_share_code(sc.strip(' \n\r\t'))
        if not ok:
            return Result.error(ResultCode.BAD_REQUEST).setMessage('Share Code Illegal').json_ret()

        dids = ShareCodeDao().getShareContent(sc)
        if len(dids) == 0:
            return Result.error(ResultCode.BAD_REQUEST).setMessage("Share Code Not Exist").json_ret()

        uuids: List[str] = DocumentDao().queryUuidByIds(uid, dids)

        if len(uuids) == 0:  # 没有文件
            return Result.error(ResultCode.SHARE_DOCUMENT_NULL).setMessage("Share Code Not Include File").json_ret()
        elif len(uuids) == 1:  # 单个文件
            filepath = os.path.join(f'{Config.UPLOAD_DOC_FOLDER}/{uid}', uuids[0])
            if not os.path.exists(filepath):
                return Result.error(ResultCode.NOT_FOUND).setMessage('File Not Found').json_ret()
            else:
                return send_file(filepath)

        else:  # 压缩文件
            filepaths = [os.path.join(f'{Config.UPLOAD_DOC_FOLDER}/{uid}', uuid) for uuid in uuids]
            existFilepaths = []  # 存在的文件
            for filepath in filepaths:
                if os.path.exists(filepath):
                    existFilepaths.append(filepath)

            time_uuid = datetime.now().strftime('%Y%m%d%H%M%S%f')
            zip_name = os.path.join(f'{Config.TEMP_SHARE_ZIP_FOLDER}', f'{time_uuid}.zip')

            # Not Exist & Create Zip
            while os.path.exists(zip_name):
                zip_name += random.randint(0, 9)
            if not FileUtil.createFile(zip_name):
                return Result.error().setMessage('Zip File Generate Failed').json_ret()

            @after_this_request
            def remove(response):
                # noinspection PyBroadException
                try:
                    os.remove(zip_name)
                except Exception as ex:
                    print(ex)
                    pass
                return response

            # noinspection PyBroadException
            try:
                with zipfile.ZipFile(zip_name, 'w', zipfile.ZIP_DEFLATED) as z:
                    for filepath in existFilepaths:
                        z.write(filename=filepath, arcname=os.path.basename(filepath))
                with open(zip_name, 'rb') as f:
                    data = f.read()
                return send_file(io.BytesIO(data), mimetype='zip', attachment_filename=f'{sc}.zip')
            except Exception:
                return Result.error().setMessage('Zip File Generate Failed').json_ret()
Пример #28
0
    def error_exception(error: TypeError):
        """
        500 Error Forwarding
        """
        print('error_exception: ', error)
        print(traceback.format_exc())

        if isinstance(error, BadSignature):
            return Result.error(ResultCode.UNAUTHORIZED).setMessage(
                "Token Bad Signature").json_ret()  # 401
        if isinstance(error, SignatureExpired):
            return Result.error(ResultCode.UNAUTHORIZED).setMessage(
                "Token Expired").json_ret()  # 401
        if isinstance(error, ParamError):
            message = 'Request Query Param Error' if error.paramType == ParamType.QUERY else \
                      'Request Route Param Error' if error.paramType == ParamType.ROUTE else \
                      'Request Form Data Param Error' if error.paramType == ParamType.FORM else \
                      'Request Raw Json Param Error' if error.paramType == ParamType.RAW else \
                      'Request Param Error'
            return Result.error(
                ResultCode.BAD_REQUEST).setMessage(message).json_ret()  # 400

        return Result.error(ResultCode.INTERNAL_SERVER_ERROR).setMessage(
            str(error)).json_ret()  # 500
Пример #29
0
 def UpdateRoute():
     """ 更新/新建 课程表 """
     try:
         schedule_data = request.form.get('schedule')
         curr_week = int(request.form.get('week'))
     except (TypeError, ValueError):
         raise ParamError(ParamType.FORM)
     if not schedule_data:
         raise ParamError(ParamType.FORM)
     if curr_week <= 0:
         raise ParamError(ParamType.FORM)
     status, new_sc, new_week = ScheduleDao().updateSchedule(
         uid=g.user, data=schedule_data, week=curr_week)
     if status == DbStatusType.FAILED or not new_sc or new_week <= 0:
         return Result.error(ResultCode.DATABASE_FAILED).setMessage(
             'Update Schedule Failed').json_ret()
     else:
         return Result.ok().putData('schedule',
                                    new_sc).putData('week',
                                                    new_week).json_ret()
Пример #30
0
    def UpdateOrderRoute():
        """ 更新顺序 """
        req_id_order = request.form.getlist('id_order')  # 3_4
        update_ids: List[int] = []
        update_orders: List[int] = []
        for id_order in req_id_order:
            try:
                id_order: [str] = id_order.split('_')
                update_ids.append(int(id_order[0]))
                update_orders.append(int(id_order[1]))
            except KeyError:
                pass

        status, count = GroupDao().updateGroupsOrder(uid=g.user,
                                                     ids=update_ids,
                                                     orders=update_orders)
        if status == DbStatusType.FAILED:
            return Result.error(ResultCode.DATABASE_FAILED).setMessage(
                "Group Update Failed").json_ret()
        else:  # Success
            return Result.ok().putData("count", count).json_ret()