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

2024-05-16 15:41:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我为一个应用程序编写了一些代码,其中一些信息存储在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 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的样子。现在我编写了一些函数来添加习惯或HabiteEvent的类对象并对它们进行分析。下面是一个例子:

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设置中分离出来。我希望有一个main.py包含ORM设置和类,还有一个analytics.py包含所有函数。当我这样做并将函数从analytics.py导入main.py并尝试调用它们时,它显然不知道习惯和习惯事件类,因为它们没有在analytics.py中定义

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


Tags: 函数pyidtruebasedatemaincolumn
2条回答

是的,它们可以分离为多个文件

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

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是要在函数中使用的模型(类)

我通过将代码拆分为多个文件来解决问题:

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

相关问题 更多 >