Пример #1
0
 def batch_upload_h(self, request_data):
     if not request_data.files:
         return False, '没有上传文件!'
     uploaded_files = request_data.files.getlist("file")
     jsdata = json.loads(request_data.form.get('data'))
     doc_id = jsdata.get('doc_id')
     commter = jsdata.get('commit_user')
     proj_id = jsdata.get('proj_id')
     if db.session.query(Ds_Doc).filter(Ds_Doc.doc_id == doc_id).order_by(Ds_Doc.doc_id).all():
         doc = db.session.query(Ds_Doc).filter(Ds_Doc.doc_id == doc_id).first()
         module = db.session.query(Model).filter(Model.model_id == doc.model_id).first()
         proj = db.session.query(Project).filter(Project.proj_id == proj_id).all()
         uti = Utillity()
         only_id = uti.get_nextval()
         file_path = os.path.abspath(os.path.join(os.getcwd(), r'data', r'doxygen', str(only_id), module.title))
         for file in uploaded_files:
             if file:
                 filename = file.filename
                 if os.path.exists(os.path.join(file_path, filename)):
                     os.remove(os.path.join(file_path, filename))
                 if not os.path.exists(file_path):
                     os.makedirs(file_path)
                 file.save(os.path.join(file_path, filename))
         success, msg = self.add_one_by_batch(file_path, proj[0].proj_name, only_id, module.title)
         if success:
             # upgrade, h_id = self.have_hurl_by_doc(doc_id)
             # if upgrade:
             #     url = self.chang_header_file(msg, doc_id, h_id)
             # else:
             url = self.add_header_flie(msg, doc_id)
             return True, url
         else:
             return False, msg
Пример #2
0
 def convert_excel_htm(self, local_file_path, new_file_name, file_path):
     """保存,以htm后缀存取"""
     # from win32com.client import Dispatch
     from win32com.client import DispatchEx
     import pythoncom
     # from win32com.client import constants
     pythoncom.CoInitialize()
     xl = DispatchEx('Excel.Application')
     # xl = Dispatch('Excel.Application')
     xl.DisplayAlerts = False
     wb = xl.Workbooks.Open(local_file_path)
     # 创建新的文件夹用来装转后的htm文件(一个网页一个文件夹)
     uti = Utillity()
     only_id = uti.get_nextval()
     file_dir = os.path.join(file_path, str(only_id),
                             os.path.splitext(new_file_name)[0])
     if not os.path.exists(file_dir):
         os.makedirs(file_dir)
     t_path = os.path.join(file_dir, os.path.splitext(new_file_name)[0])
     print(t_path)
     wb.SaveAs(t_path, FileFormat=44)  # 保存在Z盘 新文件夹下, constants.xlHtml==44
     # xl.Application.Run("SaveHTML")
     xl.Workbooks.Close()
     xl.Quit()
     del xl
     return file_dir
Пример #3
0
 def do_export(self,
               proj_id=None,
               model_id=None,
               doc_type=None,
               doc_id=None):
     msg, file_path = '', ''
     _, proj_list = CtrlProject().get(proj_id)
     if proj_list:
         self.proj_name = proj_list[0].get("proj_name")
     else:
         msg = '指定的项目不存在!'
         return False, msg, file_path
     if doc_id:  # 导出一个文档
         doc_data = CtrlDsDoc().get_doc(doc_id, detail=False)
         if not doc_data:
             msg = '不存在文档。doc_id = %s' % doc_id
             return False, msg, file_path
         doc_type = doc_data.get("doc_type")
         export_obj = ExportFactory.create(self.proj_name, doc_type)
         unique = str(Utillity.get_nextval('doc_export_seq'))
         out_dir = os.path.join(EXPORT_ROOT_DIR, unique)
         file_path = export_obj.do_export(out_dir, doc_id)
         return True, msg, file_path
     elif doc_type:  # 模块下的基本设计or详细设计
         doc_type = doc_type.upper()
         if not model_id:
             msg = '没有指定Model.'
             return False, msg, file_path
         if not proj_id:
             msg = '没有指定项目.'
             return False, msg, file_path
         if doc_type not in DOC_TYPE_DIR:
             msg = '指定的文档类型不对. type=%s' % doc_type
             return False, msg, file_path
         model = self._get_model(model_id)
         if model:
             model_name = model.get("title")
         else:
             msg = '指定的Model不对.'
             return False, msg, file_path
         unique = str(Utillity.get_nextval('doc_export_seq'))
         root_dir = os.path.join(EXPORT_ROOT_DIR, unique,
                                 DOC_TYPE_DIR.get(doc_type))
         model_name = model_name.replace(' ', '_')
         out_dir = os.path.join(root_dir, model_name)
         export_obj = ExportFactory.create(self.proj_name, doc_type)
         for doc_info in self._get_docs(proj_id, model_id, doc_type):
             doc_id = doc_info.get("doc_id")
             export_obj.do_export(out_dir, doc_id)
         # 压缩文件夹
         file_path = zip_file([out_dir], root_dir, '%s.zip' % model_name)
         return True, msg, file_path
     elif model_id:  # 模块下的所有文档
         if not proj_id:
             msg = '没有指定项目.'
             return False, msg, file_path
         return self._export_model_docs(proj_id, model_id)
     elif proj_id:  # 项目下的所有文档
         return self._export_proj_docs(proj_id)
     return True, msg, file_path
Пример #4
0
 def post(self):
     """上传图片
     :return:
     """
     result = {"result": "OK", "content": '', 'error': ''}
     try:
         file_upload = request.files['file']
         file_name = file_upload.filename
         # file_path = os.path.join('data', 'Image')
         curr_app = current_app._get_current_object()
         file_path = curr_app.config.get("IMG_PATH_ROOT")
         if not os.path.exists(file_path):
             os.mkdir(file_path)
         uti = Utillity()
         only_id = uti.get_nextval()
         new_file_name = Utillity.get_new_file_name(file_name, only_id)
         # new_file_name = '%s-%s' % (str(only_id), file_name)
         file_upload.save(os.path.join(file_path, new_file_name))
         file_url = os.path.join(file_path, new_file_name)
         file_url = Utillity.convert_url(
             curr_app.config.get('FILE_SRV_URL'), file_url)
         result["content"] = file_url
     except Exception as e:
         current_app.logger.error('%s' % e)
         result["error"] = str(e)
         result['result'] = "NG"
     finally:
         return result
Пример #5
0
    def post(self):
        # import pythoncom
        # pythoncom.CoInitialize()
        result = {"result": "NG", 'error': ''}
        try:
            file_upload = request.files['file']  # 前端拿文件
            file_name = file_upload.filename
            curr_app = current_app._get_current_object()
            file_path = curr_app.config.get(
                "TEMP_HTML_PATH_ROOT")  # Z:\temp\spec_html

            # 保存到的路径
            if not os.path.exists(file_path):
                os.mkdir(file_path)
            uti = Utillity()
            only_id = uti.get_nextval()
            new_file_name = file_name
            # new_file_name = Utillity.get_new_file_name(file_name, only_id)  # 给文件加上唯一id
            # new_file_name = '%s-%s' % (str(only_id), file_name)
            # local_file_path = os.path.join(file_path, new_file_name)
            temp_dir = os.path.abspath(
                os.path.join(os.getcwd(), r'docs/spec_excel/'))

            local_file_path = os.path.join(temp_dir, str(only_id))
            if not os.path.exists(local_file_path):
                os.makedirs(local_file_path)
            local_file = os.path.join(local_file_path, new_file_name)
            file_upload.save(local_file)  # 保存在本地
            # file_upload.save(os.path.join(os.path.abspath(os.path.join(os.getcwd(), r'../../docs/spec_excel')), new_file_name))

            # 把本地文件转换成htm文件
            # 保存在Z:\temp\spec_html\创建的文件夹名 下
            file_url = CtrlExcelHtm().convert_excel_htm(
                local_file, new_file_name, file_path)
            # os.remove(local_file_path)
            from shutil import rmtree
            rmtree(local_file_path)
            # cmd = "rm -rf %s" % local_file
            # print(cmd)
            # if os.system(cmd):
            #     print("delete ok")
            # content 里返回这个htm文件的位置
            # file_url = os.path.join(file_path, os.path.splitext(new_file_name)[0]+'.htm')
            # file_url = Utillity.convert_url(curr_app.config.get('FILE_SRV_URL'), file_url)
            _, file_url = os.path.splitdrive(file_url)  # 去掉盘符
            result["content"] = file_url
            result["result"] = "ok"
        except Exception as e:
            current_app.logger.error('%s' % e)
            result["error"] = str(e)
            result['result'] = "NG"
        finally:
            return result
Пример #6
0
 def replace_image_url(self, image_path):
     curr_app = current_app._get_current_object()
     if ".emf" in image_path:
         image_path = self.emf_to_jpeg(image_path)
     image_name = os.path.basename(image_path)
     uti = Utillity()
     only_id = uti.get_nextval()
     new_image_name = Utillity.get_new_file_name(image_name, only_id)
     new_image_url = os.path.join(curr_app.config.get("IMG_PATH_ROOT"),
                                  new_image_name)
     shutil.copyfile(image_path, new_image_url)
     image_url = Utillity.convert_url(curr_app.config.get('FILE_SRV_URL'),
                                      new_image_url)
     return image_url
Пример #7
0
 def add(self, request_data):
     data = dict()
     file_upload = ''
     if request_data.files:
         file_upload = request_data.files['file']
         if file_upload:
             file_name = file_upload.filename
             curr_app = current_app._get_current_object()
             path = curr_app.config.get("DOC_PATH_ROOT")
             if not os.path.exists(path):
                 os.makedirs(path)
             path = os.path.join(path, file_name)
             if os.path.exists(path):
                 current_app.logger.error('文件已经存在! %s' % file_name)
                 return False, u'文件已经存在!'
             file_upload.save(path)  # 保存上传的文件
             path = Utillity.convert_url(
                 curr_app.config.get('FILE_SRV_URL'), path)
             data["doc_type"] = DOC_TYPE_FILE
             data["doc_title"] = request_data.form.get('doc_title')
             # data["doc_type"] = request_data.form.get('doc_type')
             data["ver"] = request_data.form.get('ver')
             data["author"] = request_data.form.get('author')  # 作者',
             data["committer"] = request_data.form.get('committer')  # 提交者'
             data["tags"] = request_data.form.get('tags')
             if data["tags"]:
                 data["tags"] = data["tags"].split(',')
             data["summary"] = request_data.form.get("summary")
             data["keywords"] = request_data.form.get("keywords")
         else:
             return False, u'缺少文件!'
     else:
         data = request_data.get_json()
         data["doc_type"] = DOC_TYPE_URL
         if 'Tags' in data:
             data["tags"] = data.get("Tags")
         path = data.get("path")
     if not path:
         data["doc_type"] = DOC_TYPE_TEXT
         content = data.get("content")
         if not content:
             return False, u'请指定Url或上传文件或输入文本!'
         path = content
     try:
         if 'path' in data:
             data.pop("path")
         if 'file' in data:
             data.pop('file')
         data["content"] = path
         data["update_time"] = self.get_current_time()
         data["create_time"] = data["update_time"]
         self._common_add(data, data["update_time"])
         return True, 'OK'
     except Exception as e:
         # current_app.logger.info('DownLoad file path=%s, %s' % (path_info, file_name))
         db.session.rollback()
         current_app.logger.error('%s' % e)
         if file_upload:
             os.remove(path)  # 删除文件
         return False, "服务异常!请联系管理员!"
Пример #8
0
 def add2(self, attach_info, commit=True):
     ver = attach_info.get(DSAttach.ver.name)
     attach_info[DSAttach.ver.name] = Utillity.get_new_version(ver)
     attach_info = self.init_version(attach_info, type='section')
     # attach = DSAttach(**attach_info)
     # db.session.add(attach)
     log_dict = self.common_add(self.db_object, attach_info, None,
                                self.col_list, self.key_col)
     if commit:
         db.session.commit()
     else:
         db.session.flush()
     return log_dict
Пример #9
0
 def do_import(self, request_data):
     if not request_data.files:
         return False, '没有上传文件!'
     file_upload = request_data.files['file']
     if not file_upload:
         return False, '没有指定上传的文件!'
     file_name = file_upload.filename
     # if "&" in file_name:
     #     return False, '文件名不能含有&符号!'
     only_id = Utillity.get_nextval()
     new_file_name = Utillity.get_new_file_name(file_name, only_id)
     only_file_name = os.path.splitext(new_file_name)[0]
     path = os.path.join("import_root", only_file_name)
     if not os.path.exists(path):
         os.makedirs(path)
     file_url = os.path.join(path, file_name)
     file_upload.save(file_url)
     proj_id = request_data.form.get('proj_id')
     model_id = request_data.form.get('model_id')
     creator = request_data.form.get('creator')
     doc_type = request_data.form.get('doc_type')
     import_obj = ImportDocBase()
     try:
         json_url, error = import_obj.excel_to_json(file_url)
         if error:
             return False, error
         commit_list, error = import_obj.read_json(json_url, model_id, creator, doc_type, proj_id)
         if error:
             db.session.rollback()
             return False, error
         self.commit_log(commit_list, creator, self.get_current_time())
         db.session.commit()
         from app.db import cache
         cache.delete('get_model_tree')  # 删除缓存
         return True, None
     except Exception as e:
         db.session.rollback()
         current_app.logger.error('%s' % e)
         return False, "服务异常!请联系管理员!"
Пример #10
0
 def add(self, request_data, commit=True):
     if not request_data.files:
         return False, '没有上传文件!'
     file_upload = request_data.files['file']
     if not file_upload:
         return False, '没有指定上传的文件!'
     file_name = file_upload.filename
     curr_app = current_app._get_current_object()
     file_path = curr_app.config.get("ATTACH_PATH_ROOT")
     # file_path = os.path.join('data', 'Astah')
     if not os.path.exists(file_path):
         os.mkdir(file_path)
     only_id = Utillity().get_nextval()
     new_file_name = Utillity.get_new_file_name(file_name, only_id)
     fname, ext_name = Utillity.split_ext_name(file_name)
     fname = fname.rstrip('.')
     file_upload.save(os.path.join(file_path, new_file_name))
     file_url = os.path.join(file_path, new_file_name)
     file_url = Utillity.convert_url(curr_app.config.get('FILE_SRV_URL'),
                                     file_url)
     update_time = datetime.datetime.now()
     commit_time = update_time
     attach_info = {
         DSAttach.file_name.name: file_name,
         DSAttach.file_type.name: ext_name,
         DSAttach.file_url.name: file_url,
         DSAttach.update_time.name: update_time,
         DSAttach.commit_time.name: commit_time
     }
     attach = DSAttach(**attach_info)
     db.session.add(attach)
     if commit:
         db.session.commit()
     else:
         db.session.flush()
     return True, attach.to_dict()
Пример #11
0
 def _export_model_docs(self, proj_id, model_id=None):
     msg, file_path = '', ''
     model_df = self._get_model_df(proj_id)
     model_df.fillna(value=0, inplace=True)
     if model_id:
         root_models = [model_id]
         model_name = self._get_model_name(model_df, model_id)
         if not model_name:
             msg = '指定的模块不存在!'
             return False, msg, file_path
         zip_name = '%s.zip' % model_name
     else:
         root_df = model_df[model_df["parent_model_id"] == 0]
         root_models = list(root_df["model_id"].unique())
         zip_name = '%s.zip' % self.proj_name
     unique = str(Utillity.get_nextval('doc_export_seq'))
     root_dir = os.path.join(EXPORT_ROOT_DIR, unique)
     basic_obj = ExportFactory.create(self.proj_name, "BASIC")
     detail_obj = ExportFactory.create(self.proj_name, "DETAIL")
     for model_id in root_models:
         model_name = self._get_model_name(model_df, model_id)
         for model_names, leaf_model_id in self._get_models(
                 model_df, model_id, model_name):
             model_names = [n.replace(' ', '_') for n in model_names]
             model_dir = os.path.sep.join(model_names)
             for doc_type, export_obj in zip(["BASIC", "DETAIL"],
                                             [basic_obj, detail_obj]):
                 out_dir = os.path.join(root_dir,
                                        DOC_TYPE_DIR.get(doc_type),
                                        model_dir)
                 leaf_model_id = int(leaf_model_id)
                 for doc_info in self._get_docs(proj_id, leaf_model_id,
                                                doc_type):
                     doc_id = doc_info.get("doc_id")
                     export_obj.do_export(out_dir, doc_id)
     # 压缩文件夹
     in_dir_list = []
     for doc_type_dir in DOC_TYPE_DIR.values():
         in_dir = os.path.join(root_dir, doc_type_dir)
         if os.path.isdir(in_dir):
             in_dir_list.append(in_dir)
     if in_dir_list:
         file_path = zip_file([root_dir], root_dir, zip_name)
         return True, msg, file_path
     else:
         msg = '没有设计书!'
         return False, msg, file_path
Пример #12
0
 def update(self, attach_id, attach_info, commit=True):
     # attach = db.session.query(DSAttach.attach_id == attach_id).first()
     # new_ver = attach_info.get(DSAttach.ver.name)
     # attach.ver = Utillity.get_new_version(new_ver, attach.ver)
     # attach.micro_ver = self.update_version(attach.micro_ver)
     # attach.update(attach_info)
     attach = db.session.query(DSAttach.attach_id == attach_id).first()
     old_attach = attach.to_dict()
     new_ver = attach_info.get(DSAttach.ver.name)
     attach_info[DSAttach.ver.name] = Utillity.get_new_version(
         new_ver, old_attach.get(DSAttach.ver.name))
     attach_info[DSAttach.micro_ver.name] = self.update_version(
         old_attach.get(DSAttach.micro_ver.name))
     log_dict = self.common_add(self.db_object, attach_info, old_attach,
                                self.col_list, self.key_col)
     if commit:
         db.session.commit()
     return log_dict, attach_info
Пример #13
0
def get_sheet_details(file_path):
    """
    获取excel的sheet的名称
    :param file_path: 文件路径 + 文件名
    :return: 正常退出True,sheet_name的list
            异常退出 False,临时生成文件的路径
    """
    sheets = []
    # remove_files()
    only_id = Utillity.get_nextval()
    file_name = os.path.splitext(os.path.split(file_path)[-1])[0]
    file_name = '[' + str(only_id) + ']' + file_name
    # Make a temporary directory with the file name
    directory_to_extract_to = os.path.join(os.getcwd(), 'temp', file_name)
    if os.path.exists(directory_to_extract_to):
        shutil.rmtree(directory_to_extract_to)
    os.mkdir(directory_to_extract_to)

    # Extract the xlsx file as it is just a zip file
    try:
        zip_ref = zipfile.ZipFile(file_path, 'r')
        zip_ref.extractall(directory_to_extract_to)
        zip_ref.close()

        # Open the workbook.xml which is very light and only has meta data, get sheets from it
        path_to_workbook = os.path.join(directory_to_extract_to, 'xl',
                                        'workbook.xml')
        with open(path_to_workbook, 'r', encoding='utf-8') as f:
            xml = f.read()
            dictionary = xmltodict.parse(xml)
            for sheet in dictionary['workbook']['sheets']['sheet']:
                sheets.append(sheet['@name'])

        # Delete the extracted files directory
        shutil.rmtree(directory_to_extract_to)
        return True, sheets
    except Exception as e:
        return False, directory_to_extract_to
Пример #14
0
 def diff_section_image(self, new_content, old_content):
     """
     比较新旧图片是否相同,相同使用旧图片,不同拷贝新图片到文件服务器
     并使用新地址
     :param new_content:
     :param old_content:
     :return:
     """
     new_content_json = json.loads(new_content)
     old_content_json = json.loads(old_content)
     new_file_list = new_content_json[0].get('fileList')
     old_file_list = old_content_json[0].get('fileList')
     for image in new_file_list:
         new_url = image.get("url")
         index = new_file_list.index(image)
         if index < len(old_file_list):
             old_url = old_file_list[index].get("url")
             result = Utillity.diff_image(new_url, old_url)
             if result:
                 image["url"] = old_url
                 continue
         image["url"] = self.replace_image_url(new_url)
     new_content = json.dumps(new_content_json, ensure_ascii=False)
     return new_content
Пример #15
0
 def add(self, request_data):
     from app.ctrl.ctrl_ds_doc import CtrlDsDoc
     if not request_data.files:
         return False, '没有上传文件!'
     file_upload = request_data.files['file']
     if not file_upload:
         return False, '没有指定上传的文件!'
     doc_id = request_data.form.get('doc_id')
     doc_data, error = CtrlDsDoc().ds_doc_exist(doc_id)
     if error:
         return False, error
     file_name = file_upload.filename
     curr_app = current_app._get_current_object()
     file_path = curr_app.config.get("ATTACH_PATH_ROOT")
     # file_path = os.path.join('data', 'Astah')
     if not os.path.exists(file_path):
         os.mkdir(file_path)
     fname, ext_name = Utillity.split_ext_name(file_name)
     # TODO@hcz: 所有都可以
     # if not ext_name or ext_name.lower() not in (".asta", ".jude"):
     #     return False, '文件扩展名不对,请上传".asta"或".jude文件"'
     fname = fname.rstrip('.')
     # 获取新的文件名称
     only_id = Utillity().get_nextval()
     new_file_name = Utillity.get_new_file_name(file_name, only_id)
     file_upload.save(os.path.join(file_path, new_file_name))
     file_url = os.path.join(file_path, new_file_name)
     file_url = Utillity.convert_url(curr_app.config.get('FILE_SRV_URL'),
                                     file_url)
     attach_id = request_data.form.get("attach_id")
     committer = request_data.form.get("committer")  # 提交者'
     ver = request_data.form.get("ver")
     update_time = datetime.datetime.now()
     commit_time = update_time
     attach_info = {
         DSAttach.attach_id.name: attach_id,
         DSAttach.file_name.name: file_name,
         DSAttach.file_type.name: ext_name,
         DSAttach.file_url.name: file_url,
         DSAttach.update_time.name: update_time,
         DSAttach.committer.name: committer,
         DSAttach.ver.name: ver
     }
     commit_list = []
     if attach_id:  # 更新
         log_dict, attach_info = CtrlDSAttach().update(attach_id,
                                                       attach_info,
                                                       commit=False)
         if log_dict:
             commit_list.append(log_dict)
     else:  # 新增
         # 添加附件
         attach_info[DSAttach.commit_time.name] = commit_time
         attach_log = CtrlDSAttach().add2(attach_info, commit=False)
         attach_id = attach_log.get('key_id')
         attach_info[DSAttach.attach_id.name] = attach_id
         attach_info[DSAttach.commit_time.name] = self.time_to_str(
             commit_time)
         attach_info[DSAttach.update_time.name] = self.time_to_str(
             commit_time)
         astah_rel_info = {
             DSDocAstahRel.doc_id.name: doc_id,
             DSDocAstahRel.attach_id.name: attach_id
         }
         astah_rel_log = self.common_add(DSDocAstahRel, astah_rel_info,
                                         None, [], DSDocAstahRel.gid)
         commit_list.append(attach_log)
         commit_list.append(astah_rel_log)
     if commit_list:
         log_doc = CtrlDsDoc().update_ver(doc_id, committer)
         commit_list.append(log_doc)
     self.commit_log(commit_list, committer, update_time)
     db.session.commit()
     return True, attach_info
Пример #16
0
 def update(self, request_data):
     data = dict()
     need_del_old_file = False
     if request_data.files:
         file_upload = request_data.files['file']
         if file_upload:
             data["doc_id"] = request_data.form.get('doc_id')
             old_doc_info = self.get_by_key_id(data.get('doc_id'))
             if not old_doc_info:
                 return False, u'没有这个文件!'
             file_name = file_upload.filename
             curr_app = current_app._get_current_object()
             path = curr_app.config.get("DOC_PATH_ROOT")
             if not os.path.exists(path):
                 os.makedirs(path)
             path = os.path.join(path, file_name)
             if old_doc_info.get("content") != path and old_doc_info.get(
                     "doc_type") == "file":  # 文件变化了, 旧的要删除
                 need_del_old_file = True
             file_upload.save(path)  # 保存上传的文件
             path = Utillity.convert_url(
                 curr_app.config.get('FILE_SRV_URL'), path)
             data["doc_type"] = DOC_TYPE_FILE
             data["doc_title"] = request_data.form.get('doc_title')
             # data["doc_type"] = request_data.form.get('doc_type')
             data["ver"] = request_data.form.get('ver')
             data["author"] = request_data.form.get('author')  # 作者',
             data["committer"] = request_data.form.get('committer')  # 提交者'
             data["tags"] = request_data.form.get('tags')
             if data["tags"]:
                 data["tags"] = data["tags"].split(',')
             data["summary"] = request_data.form.get("summary")
             data["keywords"] = request_data.form.get("keywords")
         else:
             return False, u'缺少文件!'
     else:
         data = request_data.get_json()
         if 'file_name' in data:
             data.pop("file_name")
         old_doc_info = self.get_by_key_id(data.get('doc_id'))
         if not old_doc_info:
             return False, u'没有这个文件!'
         # data["doc_type"] = DOC_TYPE_URL
         if 'Tags' in data:
             data["tags"] = data.get("Tags")
         path = data.get("path")
     if not path:
         # data["doc_type"] = DOC_TYPE_TEXT
         content = data.get("content")
         # if not content:
         #     return False, u'请指定Url或上传文件或输入文本!'
         path = content
     try:
         if need_del_old_file:  # 删除旧的文件
             self._delete_file(old_doc_info.get("doc_type"),
                               old_doc_info.get("content"))
         if 'path' in data:
             data.pop("path")
         if 'file' in data:
             data.pop('file')
         if path:
             data["content"] = path
         else:
             if 'content' in data:
                 data.pop('content')
         data["update_time"] = self.get_current_time()
         # data["create_time"] = data["update_time"]
         self._common_add(data, data["update_time"], old_doc_info)
         return True, 'OK'
     except Exception as e:
         db.session.rollback()
         current_app.logger.error('%s' % e)
         if file_upload:
             os.remove(path)  # 删除文件
         return False, "服务异常!请联系管理员!"
Пример #17
0
 def add_one_by_batch(self, curr_app, file_path, file_name, proj_id, spec_type, spec_ver):
     fname, ext_name = Utillity.split_ext_name(file_name)
     fname = fname.rstrip('.')
     spec_name = fname
     spec_num = re.search(r'(_[0-9]+_([0-9]+_)*)', fname, flags=0).group().strip("_")
     proj = db.session.query(Project).filter(Project.proj_id == proj_id).all()
     files = {'file': open(os.path.join(file_path, file_name), 'rb')}
     html_data = requests.post(curr_app.config.get('EXCEL_TO_HTM_URL'), files=files)
     if not html_data.status_code == 200:
         return False, file_name, 'EXCEL转换HTM调用失败'
     dd = json.loads(html_data.text)
     if dd.get("result") == "ok":
         html_url = dd.get("content")
         if not platform.system() == 'Windows':
             html_url = html_url.replace('\\', '/')
             html_url = html_url.lstrip('/')
         html_url = os.path.join(curr_app.config.get('SPEC_CHANGE_URL'), html_url)
         new_htm_url = os.path.join(curr_app.config.get('SPEC_PATH_ROOT'), proj[0].proj_name,
                                    spec_type, spec_ver, 'html')
         if not os.path.exists(new_htm_url):
             os.makedirs(new_htm_url)
         mv = 'mv %s %s' % (html_url, new_htm_url)
         os.system(mv)
         new_htm_url = self.convert_url(new_htm_url)
         new_excel_url = os.path.join(curr_app.config.get('SPEC_PATH_ROOT'), proj[0].proj_name,
                                      spec_type, spec_ver, 'excel')
         file_url = os.path.join(file_path, file_name)
         if not os.path.exists(new_excel_url):
             os.makedirs(new_excel_url)
         cmd = 'cp -f %s %s' % (file_url, new_excel_url)
         os.system(cmd)
         pk_excel_url = os.path.join(new_excel_url, file_name)
         new_excel_url = self.convert_url(new_excel_url)
         update_time = datetime.datetime.now()
         # commit_time = update_time
         search_str = "[%s]-%s-%s" % (spec_type, fname, spec_name)
         inputs = db.session.query(Specification).filter(Specification.proj_id == proj_id,
                                                         Specification.spec_name == spec_name).order_by(
             Specification.spec_id).all()
         search_obj = SpecSearch.instance()
         if not inputs:
             spec_info = {Specification.proj_id.name: proj_id,
                          Specification.spec_name.name: spec_name,
                          Specification.spec_file_name.name: file_name,
                          Specification.spec_type.name: spec_type,
                          Specification.spec_num.name: spec_num,
                          Specification.search_str.name: search_str,
                          }
             attach = Specification(**spec_info)
             db.session.add(attach)
             db.session.flush()
             ver_info = {
                 SpecVersion.excel_url.name: os.path.join(new_excel_url, file_name),
                 SpecVersion.html_url.name: os.path.join(new_htm_url, fname, fname + '.htm'),
                 SpecVersion.spec_id.name: attach.spec_id,
                 SpecVersion.spec_ver.name: spec_ver,
                 SpecVersion.create_time.name: update_time,
             }
             attach2 = SpecVersion(**ver_info)
             db.session.add(attach2)
             db.session.commit()
             search_obj.add_document4excel(proj[0].proj_name, pk_excel_url, attach.spec_id, attach2.html_url)
             return True, file_name, ''
         else:
             height_ver = self.search_height_version(inputs[0].spec_id, spec_ver)
             version = db.session.query(SpecVersion).filter(SpecVersion.spec_id == inputs[0].spec_id,
                                                            SpecVersion.spec_ver == spec_ver).order_by(
                 SpecVersion.spec_id).all()
             if not version:
                 ver_info = {
                     SpecVersion.excel_url.name: os.path.join(new_excel_url, file_name),
                     SpecVersion.html_url.name: os.path.join(new_htm_url, fname, fname + '.htm'),
                     SpecVersion.spec_id.name: inputs[0].spec_id,
                     SpecVersion.spec_ver.name: spec_ver,
                     SpecVersion.create_time.name: update_time,
                 }
                 attach = SpecVersion(**ver_info)
                 db.session.add(attach)
                 db.session.commit()
                 if height_ver:
                     search_obj.add_document4excel(proj[0].proj_name, pk_excel_url, inputs[0].spec_id, attach.html_url)
                 return True, file_name, ''
             else:
                 return False, file_name, '已存在相同版本'
     else:
         return False, file_name, 'EXCEL转换HTM调用失败'
Пример #18
0
    def add(self, request_data, commit=True):
        if not request_data.files:
            return False, '没有上传文件!'
        file_upload = request_data.files['file']
        proj_id = request_data.form.get('proj_id')
        spec_name = request_data.form.get('spec_name')
        spec_type = request_data.form.get('spec_type')
        spec_num = request_data.form.get('spec_num')
        spec_ver = str(request_data.form.get('spec_ver'))
        spec_id = request_data.form.get('spec_id')
        if request_data.form.get('replace') == 'true':
            replace = True
        else:
            replace = False
        if not file_upload:
            return False, '没有指定上传的文件!'
        file_name = file_upload.filename
        file_name = file_name.replace(' ', '').replace('(', '').replace(')', '')
        curr_app = current_app._get_current_object()
        file_path = curr_app.config.get("SPEC_PATH_TEMP")
        if not os.path.exists(file_path):
            os.mkdir(file_path)
        fname, ext_name = Utillity.split_ext_name(file_name)
        fname = fname.rstrip('.')
        if os.path.exists(os.path.join(file_path, file_name)):
            os.remove(os.path.join(file_path, file_name))
        file_upload.save(os.path.join(file_path, file_name))
        proj = db.session.query(Project).filter(Project.proj_id == proj_id).all()
        files = {'file': open(os.path.join(file_path, file_name), 'rb')}
        html_data = requests.post(curr_app.config.get('EXCEL_TO_HTM_URL'), files=files)
        if not html_data.status_code == 200:
            return False, 'EXCEL转换HTM调用失败'
        dd = json.loads(html_data.text)
        if dd.get("result") == "ok":
            html_url = dd.get("content")
            if not platform.system() == 'Windows':
                html_url = html_url.replace('\\', '/')
                html_url = html_url.lstrip('/')
            html_url = os.path.join(curr_app.config.get('SPEC_CHANGE_URL'), html_url)
            new_htm_url = os.path.join(curr_app.config.get('SPEC_PATH_ROOT'), proj[0].proj_name,
                                       spec_type, spec_ver, 'html')
            if not os.path.exists(new_htm_url):
                os.makedirs(new_htm_url)
            mv = 'mv %s %s' % (html_url, new_htm_url)
            os.system(mv)
            new_htm_url = self.convert_url(new_htm_url)
            # SpecSearch
            new_excel_url = os.path.join(curr_app.config.get('SPEC_PATH_ROOT'), proj[0].proj_name,
                                         spec_type, spec_ver, 'excel')
            file_url = os.path.join(file_path, file_name)
            if not os.path.exists(new_excel_url):
                os.makedirs(new_excel_url)
            cmd = 'cp -f %s %s' % (file_url, new_excel_url)
            os.system(cmd)
            pk_excel_url = os.path.join(new_excel_url, file_name)

            new_excel_url = self.convert_url(new_excel_url)
            update_time = datetime.datetime.now()
            # commit_time = update_time
            search_str = "[%s]-%s-%s" % (spec_type, fname, spec_name)
            data = {}
            inputs = db.session.query(Specification).filter(Specification.spec_id == spec_id).order_by(
                                                            Specification.spec_id).all()
            search_obj = SpecSearch.instance()
            if not inputs:
                spec_info = {Specification.proj_id.name: proj_id,
                             Specification.spec_name.name: spec_name,
                             Specification.spec_file_name.name: file_name,
                             Specification.spec_type.name: spec_type,
                             Specification.spec_num.name: spec_num,
                             Specification.search_str.name: search_str,
                             }
                attach = Specification(**spec_info)
                db.session.add(attach)
                db.session.flush()
                ver_info = {
                    SpecVersion.excel_url.name: os.path.join(new_excel_url, file_name),
                    SpecVersion.html_url.name: os.path.join(new_htm_url, fname, fname+'.htm'),
                    SpecVersion.spec_id.name: attach.spec_id,
                    SpecVersion.spec_ver.name: spec_ver,
                    SpecVersion.create_time.name: update_time,
                }
                attach2 = SpecVersion(**ver_info)
                db.session.add(attach2)
                data = attach2.to_dict()
                data['create_time'] = self.time_to_str(data.get('create_time'))
                db.session.commit()
                search_obj.add_document4excel(proj[0].proj_name, pk_excel_url, attach.spec_id, attach2.html_url)
                return True, data
            else:
                height_ver = self.search_height_version(spec_id, spec_ver)
                if not replace:
                    version = db.session.query(SpecVersion).filter(SpecVersion.spec_id == spec_id,
                                                                   SpecVersion.spec_ver == spec_ver).order_by(
                        SpecVersion.spec_id).all()
                    if not version:
                        ver_info = {
                                     SpecVersion.excel_url.name: os.path.join(new_excel_url, file_name),
                                     SpecVersion.html_url.name: os.path.join(new_htm_url, fname, fname+'.htm'),
                                     SpecVersion.spec_id.name: spec_id,
                                     SpecVersion.spec_ver.name: spec_ver,
                                     SpecVersion.create_time.name: update_time,
                                     }
                        attach = SpecVersion(**ver_info)
                        db.session.add(attach)
                        data = attach.to_dict()
                        data['create_time'] = self.time_to_str(data.get('create_time'))
                        db.session.commit()
                        if height_ver:
                            search_obj.add_document4excel(proj[0].proj_name, pk_excel_url, spec_id,
                                                          attach.html_url)
                        return True, data
                    else:
                        return False, '已存在相同版本'
                else:
                    if db.session.query(SpecVersion).filter(SpecVersion.spec_id == spec_id,
                                                            SpecVersion.spec_ver == spec_ver).order_by(
                                SpecVersion.create_time.desc()).all():
                        attach = db.session.query(SpecVersion).filter(SpecVersion.spec_id == spec_id,
                                                                      SpecVersion.spec_ver == spec_ver).order_by(
                            SpecVersion.create_time.desc()).first()
                        attach.excel_url = os.path.join(new_excel_url, file_name),
                        attach.html_url = os.path.join(new_htm_url, fname, fname+'.htm'),
                        attach.create_time = update_time,
                        data = attach.to_dict()
                        data['create_time'] = self.time_to_str(data.get('create_time')[0])
                        db.session.commit()
                        if height_ver:
                            search_obj.add_document4excel(proj[0].proj_name, pk_excel_url, spec_id,
                                                          attach.html_url)
                        return True, data
                    else:
                        return False, '没有此版本信息,无法更新'
        else:
            return False, dd.get("error")