gis导出相关

这段代码主要实现了从GIS数据库查询数据并格式化为GeoJSON,然后将GeoJSON转换为SHP文件的过程。使用了ogr2ogr工具进行转换,并处理了中文编码问题。最后,将SHP文件夹压缩为ZIP并删除中间文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

gis相关

导出shp

查询出gis数据并格式化成geojson

SELECT row_to_json(fc)
FROM (SELECT 'FeatureCollection' AS type, array_to_json(array_agg(f)) AS features
      FROM (SELECT 'Feature' AS type, ST_AsGeoJSON(geom)::json as geometry, (SELECT row_to_json(t) FROM (SELECT  g.tbid, g.js_dkmj) AS t) AS properties
            FROM gis表名 g 
            where g.tbid NOTNULL and g.tbid != '' %(where)s ) AS f
     ) AS fc

geojson转shp

    sql = """SELECT row_to_json(fc)
FROM (SELECT 'FeatureCollection' AS type, array_to_json(array_agg(f)) AS features
      FROM (SELECT 'Feature' AS type, ST_AsGeoJSON(geom)::json as geometry, (SELECT row_to_json(t) FROM (SELECT  g.tbid, g.js_dkmj) AS t) AS properties
            FROM gis 表名 g 
            where g.tbid NOTNULL and g.tbid != '' %(where)s ) AS f
     ) AS fc """ % {'where': where}

    body = fetchone_sql(sql, flat=True)

    file_name = 'xzwt_slsj'
    # 读取body,json格式存储到文件中
    now = datetime.datetime.now()
    json_dest = os.path.join(MEDIA_ROOT, "shp", now.strftime('%Y%m%d'),
                             file_name + now.strftime('%Y%m%d%H%M%S') + '.geojson')
    if not os.path.exists(os.path.dirname(json_dest)):
        os.makedirs(os.path.dirname(json_dest))
    open(json_dest, 'w+').write(json.dumps(body))

    # 将json中的内容转换到shp中, 如果失败(例如中文超长的问题出现)返回导出失败
    dest = os.path.join(os.path.dirname(json_dest), file_name + now.strftime('%Y%m%d%H%M%S'))
    if not os.path.exists(dest):
        os.makedirs(dest)
    # cmd = 'python3 %s --json=%s --dest=%s' % (os.path.join(BASE_DIR, 'utils', 'geojson2shp.py'), json_dest, dest)
    cmd = '''ogr2ogr -t_srs "EPSG:4490" -overwrite %s/%s.shp  %s --config SHAPE_ENCODING "GBK"''' % (
    dest, os.path.basename(dest), json_dest)
    res = os.system(cmd)
    if res != 0:
        return json_response(code=51, msg="shp不支持此内容的导出")
    # 导出成功 将导出的文件夹压缩,删除此接口中所有用到的中间文件和文件夹(json文件、shp文件夹)
    try:
        with zipfile.ZipFile(dest + '.zip', mode='a', compression=zipfile.ZIP_DEFLATED) as zf:
            for path, dirnames, filenames in os.walk(dest):
                # 去掉目标跟路径,只对目标文件夹下边的文件及文件夹进行压缩
                fpath = path.replace(dest, '')
                for filename in filenames:
                    zf.write(os.path.join(path, filename), os.path.join(fpath, filename))
            shutil.rmtree(dest)
            os.remove(json_dest)
    except Exception as e:
        logger.error("导出shp失败", exc_info=True)
        return json_response(code=51, msg="导出失败")
    return json_response(code=5, msg="导出成功", data=os.path.relpath(dest + '.zip', MEDIA_ROOT))

json转shp封装

import datetime
import zipfile
import os
import shutil


def geojson2shp(body, file_name):
    # 读取body,json格式存储到文件中
    now = datetime.datetime.now()
    json_dest = os.path.join(MEDIA_ROOT, "shp", now.strftime('%Y%m%d'),
                             file_name + now.strftime('%Y%m%d%H%M%S') + '.geojson')
    if not os.path.exists(os.path.dirname(json_dest)):
        os.makedirs(os.path.dirname(json_dest))
    open(json_dest, 'w+').write(json.dumps(body))

    # 将json中的内容转换到shp中, 如果失败(例如中文超长的问题出现)返回导出失败
    dest = os.path.join(os.path.dirname(json_dest), file_name + now.strftime('%Y%m%d%H%M%S'))
    if not os.path.exists(dest):
        os.makedirs(dest)
    # cmd = 'python3 %s --json=%s --dest=%s' % (os.path.join(BASE_DIR, 'utils', 'geojson2shp.py'), json_dest, dest)
    cmd = '''ogr2ogr -t_srs "EPSG:4490" -overwrite %s/%s.shp  %s --config SHAPE_ENCODING "GBK"''' % (
    dest, os.path.basename(dest), json_dest)
    res = os.system(cmd)
    if res != 0:
        raise APIException(message="shp不支持此内容的导出")
    # 导出成功 将导出的文件夹压缩,删除此接口中所有用到的中间文件和文件夹(json文件、shp文件夹)
    try:
        with zipfile.ZipFile(dest + '.zip', mode='a', compression=zipfile.ZIP_DEFLATED) as zf:
            for path, dirnames, filenames in os.walk(dest):
                # 去掉目标跟路径,只对目标文件夹下边的文件及文件夹进行压缩
                fpath = path.replace(dest, '')
                for filename in filenames:
                    zf.write(os.path.join(path, filename), os.path.join(fpath, filename))
            shutil.rmtree(dest)
            os.remove(json_dest)
    except Exception as e:
        logger.error("导出shp失败", exc_info=True)
        raise APIException(message="导出失败")
    return dest
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值