Flask 和 peewee FlaskDB() "connection already opened" 与 APScheduler

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

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

在我添加 APScheduler 作业之前,一切都适用于应用程序设置。我希望在应用程序启动时以及之后每 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()

我只是不确定我到底错过了什么,在 peewee/flask 方面我还是个新手。

谢谢!

我会稍等片刻再接受我自己的答案,因为我确信有一个潜在的 better/proper 解决方案。

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

我不确定是不是因为在代码 运行s 时数据库还没有初始化,或者到底是什么原因,我确定这有点骇人听闻,但它确实清除了异常

基本上向配置添加了第二个作业(和明确的时区)

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 func

中删除了初始的 运行
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