如何将 SQLAlchemy ORM 和函数拆分为两个不同的文件

How to split up SQLAlchemy ORM and functions into two different files

我为一个应用程序编写了一些代码,其中一些信息存储在 SQLite3 数据库中。因此,我使用了 SQLAlchemy 并设置了对象关系映射器,如:

from sqlalchemy import create_engine, Column, Integer, String, ForeignKey, Date
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

# Setting up SQLAlchemy to connect to the local SQLite3 database
Base = declarative_base()
engine = create_engine('sqlite:///:main:', echo=True)
Base.metadata.create_all(bind=engine)
Session = sessionmaker(bind=engine)
session = Session()

在数据库中存储信息的两个主要 class 如下所示:

class Habit(Base):    
    __tablename__ = 'habit'
    habit_id = Column('habit_id', Integer, primary_key=True)
    name = Column('name', String, unique=True)
    periodicity = Column('periodicity', String)
    start_date = Column('start_date', Date)

class HabitEvent(Base):
    __tablename__ = 'habit_event'
    event_id = Column('event_id', Integer, primary_key=True)
    date = Column('date', Date)
    habit_id = Column('fk_habit_id', Integer, ForeignKey(Habit.habit_id))

这就是我的 main.py 的样子。现在我写了一些函数来添加 class 个 Habit 或 HabitEvent 对象并分析它们。这是一个例子:

def get_habits():
    """Lists all habits, including habit id, periodicity and start date."""
    
    habits = session.query(Habit).all()
    for habit in habits:
        print(str(habit.habit_id)+', '+str(habit.name) + ', ' 
              + str(habit.periodicity) +', Start Date: '
              + str(habit.start_date.strftime('%A, %B %d, %Y')))

现在我想将函数从 ORM 设置中分离出来。我想要一个包含 ORM 设置和 classes 的 main.py 和一个包含所有功能的 analytics.py。当我这样做并将函数从 analytis.py 导入到 main.py 并尝试调用它们时,它显然不知道 Habit 和 HabitEvent class,因为它们没有在analytics.py.

这是我的最后一个问题:是否可以将 ORM 和分析功能拆分为两个建议的文件?或者它们必须是同一个文件的一部分?

是的,它们可以分成多个文件。

一种方法是将会话和模型传递给函数:

def get_habits(session, Habit):
    """Lists all habits, including habit id, periodicity and start date."""

    habits = session.query(Habit).all()
    for habit in habits:
        print(str(habit.habit_id)+', '+str(habit.name) + ', ' 
              + str(habit.periodicity) +', Start Date: '
              + str(habit.start_date.strftime('%A, %B %d, %Y')))

并且在 main.py 文件中,您可以在导入后调用此函数,如下所示:

get_habits(session, Habit)

sessionsession = Session()Habit 是您要在函数中使用的模型 (class)。

我通过将代码分成多个文件解决了这个问题:

  • main.py 包含 CLI 并从 analytics.py
  • 导入所有函数
  • orm.py 包含对象关系映射器设置
  • classes.py 包含 orm 的 类 并从 orm.py
  • 导入 Base
  • analytics.py 包含 classes.py 的 类 的所有函数和导入以及 orm.py
  • 的会话