python - 如何在将行推送到 pgsql 之前验证行是否符合要求?
问题描述
说表结构是这样的:
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方面做了很多工作,但到目前为止有很多选择,在你的 lib 堆栈中采用那个库之前做一个很好的调查。
推荐阅读
- c - 为什么将十六进制 int 转换为 char* 会向后打印?
- linux - 带有时间戳的终端命令执行和输出日志记录
- angular - Angular Routing in Github Pages
- r - 在R包textstem中,为什么stem_word("way")返回"wai"
- python - Discord.py 货币机器人;创建银行帐户命令仅适用于使用该命令的第一人。怎么修?
- javascript - 单击按钮切换列表中的所有项目(反应)
- xcode - 丰富通知扩展 XCode 的配置文件
- sitecore - 从 web 数据库 sitecore 获取计数数据
- javascript - Openlayers 6 地理定位控制
- c# - 我的泛型类构造函数可以从传入的类型推断类型吗?