回答此问题可获得 20 贡献值,回答如果被采纳可获得 50 分。
<p>我为一个应用程序编写了一些代码,其中一些信息存储在SQLite3数据库中。因此,我使用了SQLAlchemy并设置了对象关系映射器,如:</p>
<pre><code>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()
</code></pre>
<p>数据库中存储信息的两个主要类如下所示:</p>
<pre><code>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))
</code></pre>
<p>这就是我的main.py的样子。现在我编写了一些函数来添加习惯或HabiteEvent的类对象并对它们进行分析。下面是一个例子:</p>
<pre><code>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')))
</code></pre>
<p>现在我想把这些函数从ORM设置中分离出来。我希望有一个main.py包含ORM设置和类,还有一个analytics.py包含所有函数。当我这样做并将函数从analytics.py导入main.py并尝试调用它们时,它显然不知道习惯和习惯事件类,因为它们没有在analytics.py中定义</p>
<p>这里是我的最后一个问题:是否有可能将ORM和分析函数拆分为两个建议的文件?或者它们必须是同一个文件的一部分</p>