Flask and peewee FlaskDB() "connection already opened" with APScheduler



我有一个带有peewee的烧瓶应用程序和一个池化的postgresql数据库。

一切都适用于应用程序设置,直到我添加了一个 APS调度员 作业。我希望作业在应用程序启动时和之后每 8 小时运行一次。

Flask-apscheduler 和 peewee 的配置位:

class Config(object):
JOBS =  [
{
'id': 'myjob',
'func': 'app.jobs:do_something_job',
'trigger': 'interval',
'hours': 8
}
]
SCHEDULER_API_ENABLED = True
DATABASE = 'postgresext+pool://user:password@localhost:5432/dev?max_connections=32&stale_timeout=300'

app.py:

scheduler = APScheduler()
db = FlaskDB()
def create_app(config_object=Config):
"""Application Factory Pattern"""
app = Flask(__name__.split('.')[0])
app.config.from_object(config_object)
db.init_app(app)
scheduler.init_app(app)
scheduler.start()
# RUN the job on application creation:
scheduler.run_job('myjob') # <--- exception thrown here
return app
app = create_app(Config)

该行scheduler.run_job('myjob')在应用程序启动后立即导致peewee.OperationalError: Connection already opened.(如果我在启动应用程序后不久访问该页面)

虽然,看起来初始作业运行仍然工作正常

do_something_job如下所示:

def do_something_job():
new = NewModel(seed=new_seed())
new.save()
old_list = NewModel.select()
for old in old_list:
if old.id != new.id:
expired = OldModel(seed=old.seed,
created_at=old.created_at,
expired_at=datetime.datetime.utcnow())
expired.save()
old.delete_instance()

我只是不确定我到底错过了什么,在皮尤/烧瓶方面我仍然有点新手。

谢谢!

我会等一段时间才能接受我自己的答案,因为我确信有一个可能更好/合适的解决方案。

但我基本上将 Flask-APScheduler 设置为在未来 30 秒内运行初始作业,并将其从我的 create_app() 中删除。

我不确定这是因为数据库在代码运行时尚未初始化还是确切的内容,我确定这是黑客行为,但它确实清除了异常

基本上在配置中添加了第二个作业(和显式时区)

class Config(object):
SCHEDULER_TIMEZONE = 'UTC'
JOBS =  [
{
'id': 'myinitialjob',
'func': 'app.jobs:do_something_job',
'trigger': 'date',
'run_date': datetime.datetime.utcnow() + datetime.timedelta(seconds=30)
},
{
'id': 'myjob',
'func': 'app.jobs:do_something_job',
'trigger': 'interval',
'hours': 8
}
]
SCHEDULER_API_ENABLED = True

从create_app功能中删除了初始运行

def create_app(config_object=Config):
"""Application Factory Pattern"""
app = Flask(__name__.split('.')[0])
app.config.from_object(config_object)
db.init_app(app)
scheduler.init_app(app)
scheduler.start()
# scheduler.run_job('myjob') # <--- removed this
return app

相关内容

最新更新