You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.
# -*- encoding: utf-8 -*-
'''
@File : models.py
@License : (C)Copyright 2018-2022
@Modify Time @Author @Version @Desciption
------------ ------- -------- -----------
2023/4/17 16:01 zart20 1.0 None
'''
from sqlalchemy import create_engine
from sqlalchemy . orm import scoped_session , sessionmaker
from sqlalchemy . ext . declarative import declarative_base
# create_engine函数用于创建一个数据库引擎 (engine) 对象,该对象用于与底层数据库进行通信。
engine = create_engine ( ' mysql+pymysql://root:123123@127.0.0.1/example ' )
# scoped_session 函数用于封装会话工厂,使其能够被多个线程共享。
# 使用 scoped_session 可以保证每个线程都能使用同一个会话对象,从而避免了多个线程之间的会话冲突问题。
db_session = scoped_session (
# sessionmaker 函数中指定会话的参数,包括禁用自动提交 (autocommit=False) 和自动flush (autoflush=False)。
# 这样可以在需要时手动控制 SQL 的提交和刷新机制。bind 参数指定了这个会话将要连接的数据库引擎对象。
sessionmaker (
autoflush = False ,
autocommit = False ,
bind = engine ) )
Base = declarative_base ( ) # `declarative_base` 是在 SQLAlchemy 中用于实现映射类 (ORM 类) 与表的映射关系的基类。
Base . query = db_session . query_property ( ) # 将会话工厂的 query 方法设置成了 Base 的属性 query, 这样在定义映射类时可以直接使用 Base.query 来查询数据库。
def init_db ( ) :
# 创建了所有继承自 Base 的 ORM 类所映射的表,如果表已经存在,则跳过。
# 这个函数将会自动找到所有继承自 Base 的 ORM 类,并生成对应的数据表。
# 其中 bind=engine 表示使用上面定义的数据库引擎来执行 SQL 语句,实现将 ORM 类中的属性映射为数据表中的列及其属性。
Base . metadata . create_all ( bind = engine )