Python SQLAlchemy补充模块之SQLAlchemy

2023-07-07  本文已影响0人  羋学僧

SQLAlchemy 实用程序

SQLAlchemy-Utils 为 SQLAlchemy 提供自定义数据类型和各种实用函数。

SQLAlchemy-Utils官方文档

一、安装

pip install sqlalchemy-utils

二、Data types

class User(Base):
    TYPES = [
        ('admin', 'Admin'),
        ('regular-user', 'Regular user')
    ]

    __tablename__ = 'user'
    id = sa.Column(sa.Integer, primary_key=True)
    name = sa.Column(sa.Unicode(255))
    type = sa.Column(ChoiceType(TYPES))


user = User(type='admin')
user.type  # Choice(code='admin', value='Admin')
from sqlalchemy_utils import JSONType


class Product(Base):
    __tablename__ = 'product'
    id = sa.Column(sa.Integer, autoincrement=True)
    name = sa.Column(sa.Unicode(50))
    details = sa.Column(JSONType)


product = Product()
product.details = {
    'color': 'red',
    'type': 'car',
    'max-speed': '400 mph'
}
session.commit()

三、Database helpers

database_exists('postgresql://postgres@localhost/name')  #=> False
create_database('postgresql://postgres@localhost/name')
database_exists('postgresql://postgres@localhost/name')  #=> True
create_database('postgresql://postgres@localhost/name')
create_database(engine.url)
drop_database('postgresql://postgres@localhost/name')
drop_database(engine.url)
上一篇下一篇

猜你喜欢

热点阅读