get_meta.py 4.4 KB
# coding=utf-8
# author:        4N
# createtime:    2020/9/4
# email:         nheweijun@sina.com

import traceback
from osgeo.ogr import *
from osgeo import ogr

from flask import request
import os
import uuid

import json
from app.util.component.ApiTemplate import ApiTemplate
from app.util.component.ZipUtil import ZipUtil
from app.util.component.FileProcess import FileProcess
import platform

class Api(ApiTemplate):
    api_name = "获取meta"
    def process(self):
        res = {}

        try:

            spatial_files=[]
            if self.para.get("data_path"):
                filename = os.path.basename(self.para.get("data_path"))
                #处理

                if self.para.get("data_path").endswith("zip"):

                    store_path = ZipUtil.unzip(self.para.get("data_path"),True)
                    spatial_files = FileProcess.get_spatial_file(store_path)

                elif self.para.get("data_path").endswith("shp"):
                    data_path=self.para.get("data_path")
                    encoding_cpg_path = data_path.split(".shp")[0]+".cpg"
                    if not os.path.exists(encoding_cpg_path):
                        encoding_cpg=None
                    else:
                        with open(encoding_cpg_path) as fd:
                            encoding_cpg = fd.readline().strip()

                    spatial_files.append((data_path, encoding_cpg))
                elif  self.para.get("data_path").endswith("gdb"):
                    data_path=self.para.get("data_path")
                    encoding_cpg=None
                    spatial_files.append((data_path, encoding_cpg))
                else:
                    raise Exception("文件不符合规格!")

            else:
                # 保存文件
                # 保存在项目外
                if platform.system().lower() == 'windows':
                    parent = "C:/"
                else:
                    parent = "/tmp"

                dir_path, store_file = FileProcess.save(parent)
                store_path = ZipUtil.unzip(store_file)

                spatial_files = FileProcess.get_spatial_file(store_path)

                file = request.files['file']
                filename = file.filename.split('"')[0]

            res["data"] =[]

            for data_path,code in spatial_files:
                one_data = self.get_meta(data_path)
                one_data["encoding"]=code
                one_data["filename"] = filename
                res["data"].append(one_data)
            res["result"] = True

        except Exception as e:
            raise e
        return json.dumps(res,ensure_ascii=False)


    def get_meta(self,data_path):
        ds: DataSource = None
        info = {}
        layer_name = {}
        info["data_path"] = os.path.normpath(data_path)
        info["layer"] =layer_name
        try:
            # 分为shp和gdb 2种
            if data_path.endswith("shp"):
                info["type"]="shp"
                driver: Driver = ogr.GetDriverByName("ESRI Shapefile")
                ds: DataSource = driver.Open(data_path, 0)
                if not ds:
                    raise Exception("打开数据失败!")
                layer: Layer = ds.GetLayer(0)

                layer_name[layer.GetName()] = layer.GetName()

            if data_path.endswith("gdb"):
                info["type"] = "gdb"
                driver: Driver = ogr.GetDriverByName("OpenFileGDB")
                ds: DataSource = driver.Open(data_path, 0)
                if not ds:
                    raise Exception("打开数据失败!")
                for i in range(ds.GetLayerCount()):

                    layer: Layer = ds.GetLayer(i)

                    layer_name[layer.GetName()] = layer.GetName()

        except Exception as e :
            raise e
        finally:
            if ds:
                ds.Destroy()
        return info


    api_doc={
    "tags":["IO接口"],
    "parameters":[
        {"name": "file",
         "in": "formData",
         "type":"file",
         "description":"数据文件zip压缩包"},
        {"name": "data_path",
         "in": "formData",
         "type": "string",
         "description": "数据文件路径"}
    ],
    "responses":{
        200:{
            "schema":{
                "properties":{
                }
            }
            }
        }
}