首页 > 解决方案 > 如何在将行推送到 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 中提取模式信息并对其进行验证来做到这一点?

标签: pythonpython-3.xdatabasepostgresqlvalidation

解决方案


第一步是从数据库本身检索预期的数据类型,这可以通过@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 堆栈中采用那个库之前做一个很好的调查。


推荐阅读