gpt4 book ai didi

python - 将 SQL 语句存储在属性文件中以供 Python 脚本使用?

转载 作者:行者123 更新时间:2023-12-02 06:49:38 29 4
gpt4 key购买 nike

我不知道如何最好地表达这个问题,但我会尝试。

我有几个通过 crontab 执行的 python 脚本。这些脚本执行一些数据库操作,例如选择和更新(在不同的数据库上),并且有些脚本使用相同的 SQL 语句。就目前情况而言,我使用了 SQL 查询,存储在 util.py 文件中的静态字典中,并且每当需要时我都会从不同的脚本中导入它,但是我想知道将静态 SQL 语句存储到的最佳实践是什么被不同的脚本使用?可读性很重要,因此我需要某种可以正确缩进 SQL 查询的文件格式。

最佳答案

3 个选项。

(注意:下面的 select * from t where custid = %(custid)s 之类的内容稍后将被馈送到 postgresql 参数化查询。使用 RDBMS 的参数化查询语法,切勿手动构建查询字符串 because sql injection一个非常好的理由。即使如此,也将其限制为来自应用程序本身的配置 - 位于文件系统某处的外部“数据源文件”可能会被不良行为者损坏,然后可以搭上您的应用程序凭据的便车。

配置解析器

我会使用旧的 INI/ConfigParser 格式。以前经常使用它们,但现在更倾向于 json,只不过 json 对于 sql 来说不太好。

这是Python

import ConfigParser
cfp = ConfigParser.ConfigParser()
cfp.read("test_so08.ini")
myselect = cfp.get("sql", "select", raw=True)
for line in myselect.split("\n"):
print ":%s:" % (line)

还有ini。请注意,您需要在 select= 之后的每个后续行中至少缩进一个空格,否则 configparser 将尝试解析其他行,而不是将它们与 select 分组。

[sql]
select=select *
from customers
where custid = %(custid)s
select2=<some other stuff>

打印输出:

:select *:
:from customers:
:where custid = %(custid)s:

优点:它不是代码文件,因此理论上您可以让任何人配置 sql。理论上。

缺点:基于ini的sql在获取变量方面有相当大的开销,并且当您想要添加更多功能时,您最终会做很多解决方法。

模块中的普通旧三字符串变量:

另一种选择是仅使用 Python 模块并使用三引号字符串。现在我倾向于将其用于 sql,而不是 ini。

优点:简单。
缺点:仅限 Python,无效的语法拼写错误将停止您的调用脚本。

say this is sql_test_so08.py

select = """
select *
from customers
where custid = %(custid)s
"""

select2 = """<some other stuff>"""

在你的脚本中:

import sql_test_so08
print sql_test_so08.select

一个优点是我可以使用 Template/$var 替换来替换从其他地方导入的应用程序常量,而不是在 sql 中将它们硬编码。假设您将 invalid_customer_unpaid 标志设置为 3。

在 sql.py 文件中你会喜欢:

from constants import invalid_customer_unpaid

di_constants = dict(invalid_customer_unpaid=invalid_customer_unpaid)

select_bad="""select... where ... $invalid_customer_unpaid"""

select_bad = Template(select_bad).substitute(di_constants)

注意:我很少使用直接变量替换,如此处所示。 SQL 注入(inject)的风险太大。但是您可以使用 RDBMS 的绑定(bind)参数支持来应用相同的想法。

YAML:

这些天做了更多的 YAML。

  • 用于机器写入和机器读取的 JSON。
  • YAML 适合手写、机器读取,因为它比 JSON 更能支持引号和格式。

给定test.yaml:

sql:
select: select * from customers where custid = %(custid)s
text: 'some text with ''abc'' and "xyz" '

然后

from yaml import safe_load as yload

with open("test.yaml") as fi:
di2 = yload(fi)

print (di2["sql"]["select"])

将输出:从 custid = %(custid)s 的客户中选择 *

关于python - 将 SQL 语句存储在属性文件中以供 Python 脚本使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30218963/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com