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



我为一个应用程序编写了一些代码,其中一些信息存储在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应该是什么样子。现在我写了一些函数来添加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设置和类的main.py和一个包含所有函数的analysis.py。当我这样做并将函数从analysis.py导入main.py并尝试调用它们时,它显然不知道Habit和HabitEvent类,因为它们没有在analysiss.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是要在函数中使用的模型(类(。

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

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

最新更新