Пример #1
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
Пример #2
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
Пример #3
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
Пример #4
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
Пример #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 _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
Пример #8
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, "服务异常!请联系管理员!"
Пример #9
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