第一步是从数据库本身检索预期的数据类型,这可以按照@gaurav的建议完成)使用a:
SELECT column_name, data_type FROM information_schema.columns where ...
这给你提供了类型模式,这可以作为 "验证模式 "使用。
simple example - 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
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
better approach
对于第二步,有专门的验证库,它们可以进行打字、剪切和模式验证(如2个字段的密码必须相同)以及很多有用的东西。
我曾与很多voluptuous but 许多选择到现在为止,在你的资料库中采用一个库之前,请做好调查。