如何拥有 python 类型和 sqlalchemy 列的约束?

How to have the python type and the constraints of a sqlalchemy column?

通过这样做:

    columns = [[column.name, column.type] for column in inspect(table).c]
    print(columns)

我设法获得了列的名称和类型。 但是我得到的类型是sqlalchemy格式的,不是python格式的。 我还想知道 table 是否可以为空。

例如,如果我们有这一列:

    username = Column(String(45), nullable=False)

我想要这样的东西:

    ["username", str, 45, False]

您可以从列的类型的 python_type 属性中获取 Python 类型,从 type 中获取 length,从列中获取 nullable

>>> username = sa.Column(sa.String(45), nullable=False)
>>> username.type.python_type
<class 'str'>
>>> username.type.length
45
>>> username.nullable
False