说表结构是这样的:
CREATE TABLE foo (
id INTEGER NOT NULL,
enter_time TIMESTAMP NOT NULL,
comment TEXT
);
现在在python中,说我得到这样的数据:foo_user = {"id": 123, "enter_time": None, "comment": ''}
在将其发送到 pgsql 之前,如何手动验证这些数据?是否有任何库已经通过从 pgsql 中提取模式信息并对其进行验证来做到这一点?
最佳答案
第一步是从数据库本身检索预期的数据类型,这可以完成,如@gaurav 所建议的那样)使用:
SELECT column_name, data_type FROM information_schema.columns where ...
这为您提供了类型架构,这可以用作“验证架构”简单的例子 - diy
这里有一个简单的例子,仅限于检查输入数据是否可以输入(它可能会被 postgres 以相同的方式转换)
from datetime import datetime
schema = {"id": "integer", "enter_time": "TIMESTAMP", "comment": 'text'}
def is_valid(v, validator):
# dummy validator, we try to apply a constructor
# returns only True/False,
# If False... we don't know why!
# here you can use a RE for check if input is syntactically correct
try:
validator(v)
except:
return False
else:
return True
# type to validator
binding = {'integer':int,
'TIMESTAMP': datetime.fromtimestamp,
'text':str}
#validation schemaa
val_schema = {k:binding[v] for k,v in schema.items()}
foo_user = {"id": 123, "enter_time": None, "comment": ''}
for k,v in foo_user.items():
print (k, ':', is_valid(v, val_schema[k]))
#
# id : True
# enter_time : False
# comment : True
更好的方法对于第二步,有专门的验证库,它们可以进行打字、剪辑和模式验证(例如必须相同的 2 个字段密码)和许多有用的东西。
我和 voluptuous 一起工作了很多但是 many choices到目前为止可用,在你的 lib 堆栈中采用该库之一之前,请先做一个很好的调查。
关于python - 如何在将行推送到 pgsql 之前验证它是否合规?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67800882/