栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

将SQL原样保存到YAML

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

将SQL原样保存到YAML

如果您的输入格式是一些未格式化的SQL(没有换行符和缩进空格),就像您似乎从输出(2)中 获取的那样,您将 永远不会 自动获得良好的输出:

import yamlsql = ("SELECt DISTINCT p.id_product, ""p.price AS price, ""sp.reduction AS discount, ""sp.reduction_type AS discount_type, ""pl.description_short AS description ""FROM ....")app_config = dict(sql=sql)print yaml.dump(app_config)

会给你:

{sql: 'SELECt DISTINCT p.id_product, p.price AS price, sp.reduction AS discount, sp.reduction_type    AS discount_type, pl.description_short AS description FROM ....'}

如您所知。您可以尝试使用换行符和缩进来对字符串进行手工格式化

app_config = dict(sql="""SELECt DISTINCT p.id_product,     p.price AS price,     sp.reduction AS discount,     sp.reduction_type AS discount_type,     pl.description_short AS description    FROM ....""")print yaml.dump(app_config)

但是输出并不好:

{sql: "SELECt DISTINCT p.id_product,n     p.price AS price,n                    sp.reduction AS discount,n     sp.reduction_type AS discount_type,n         pl.description_short AS descriptionn    FROM ...."}

我建议您采用其他方法,并结合ruamel.yaml(我是PyYAML增强版的作者)安装sqlparse或format-
sql之
类的sql格式化程序,该格式程序支持多行文字字符串往返。在一点帮助下,它也可以用于生成正确且更好(如果不是更好)的YAML输出。

你可以做:

import ruamel.yamlfrom ruamel.yaml.scalarstring import PreservedScalarStringimport sqlparsesql = ("SELECt DISTINCT p.id_product, "       "p.price AS price, "       "sp.reduction AS discount, "       "sp.reduction_type AS discount_type, "       "pl.description_short AS description "       "FROM ....")fsql = sqlparse.format(sql, reindent=True, keyword_case="upper").enpre('utf-8')app_config = dict(sql=PreservedScalarString(fsql))print ruamel.yaml.dump(app_config, Dumper=ruamel.yaml.RoundTripDumper)

并获得带有保留的换行符的YAML文字标量:

sql: |-  SELECt DISTINCT p.id_product,       p.price AS price,       sp.reduction AS discount,       sp.reduction_type AS discount_type,       pl.description_short AS description  FROM ....

希望距离您想要的足够近。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/431658.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号