SQLAlchemy框架基本使用

基本配置

  1. 需要安装pyodbc作为底层数据源,此处需要强调连接字符串之写法,需要指定odbc版本,勿用SQL Server,须用sql server 18,前者为mssql2000版本使用之odbc,现已不支持,标准写法为:mssql+pyodbc://sa:5016@localhost/XUEXI?driver=ODBC+Driver+18+for+SQL+Server&TrustServerCertificate=yes
  2. 使用如下程序初始化连接池等
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39

engine: Engine | None = None
SessionLocal: sessionmaker | None = None

@run_once
def init_db() -> None:
global engine, SessionLocal

if engine is not None:
return

database_url: str = (
get_options(DatabaseSettings).mssql.demo
)

engine = create_engine(
database_url,
pool_size=100,
max_overflow=10,
pool_pre_ping=True,
echo=True,
)

SessionLocal = sessionmaker(
autocommit=False,
autoflush=False,
bind=engine,
)


def get_db() -> Generator[Session, None, None]:
if SessionLocal is None:
raise RuntimeError("Database not initialized, call init_db() first")
else:
db = SessionLocal()
try:
yield db
finally:
db.close()

连接数据库并实现自动建表

  1. 在SQLAlchemy框架当中实现类型的继承(比如实现一个通用抽象父类BaseEntity)时,框架推荐使用Mixin混合设计模式,此设计模式类似于抽象类,且无法初始化,仅作为一个通用的父类使用,可提供通用方法等
  2. 通用抽象父类使用@declarative_mixin装饰器装饰
    可以参考代码如下:
1
BaseEntity = declarative_base(cls=__Entity)

其中BaseEntity就是后续类继承之基类。
3. 基类当中通常需要实现@reconstructor装饰之方法,此方法作用是
让框架从数据库查询出数据后调用,可以进行部分初始化之操作,因为框架不会调用__init__方法进行初始化,在项目当中使用主要是

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class __Entity:
def __init__(self):
if not self.domain_events:
self.domain_events = []

@reconstructor
def _after_load(self):
self.domain_events: List[DomainEvent] = []

def add_domain_event(self, domain_event: DomainEvent):
self.domain_events.append(domain_event)

def remove_domain_event(self, domain_event: DomainEvent):
self.domain_events.remove(domain_event)

def remove_all_domain_events(self):
self.domain_events = []

此处需要说明的是使用前缀下划线标注此类模块内私有,如上点所例之BaseEntity为外部使用之父类
4. 外部使用

1
BaseEntity.metadata.create_all(bind=engine)

进行自动建表