SessionLocal = sessionmaker(
bind=engine,
autocommit=False,
autoflush=False,
)
Base = declarative_base()
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
이렇게 데이터베이스 호출 부를 구성 해놓고 다른 파일에서 get_db함수를 통해 데이터베이스에 접근 할 때, 간혹 AttributeError: 'generator' object has no attribute 'query'
라는 에러를 만날 때가 있다.
그럴 땐 get_db를 next로 감싸면 된다. 위 에러는 제너레이터의 결과물이 yield 된 게 아니라, 제너레이터 그 자체가 반환 되면서 발생한 문제다. 그래서 처음 받은 값 말고 그 다음 값부터 받으면 된다.
@sched.scheduled_job('cron', hour='1', minute='30', id='remove_inactive_image')
def job():
db = next(get_db())
inactive_image_list = db.query(Image).filter(Image.state == "INACTIVE").all()
for image in inactive_image_list:
db.delete(image)