flask 定时任务(APScheduler)使用current_app app_context()上下文

前言:

描述:flask定时任务调用的方法中使用了current_app.logger.info()记录日志报错

报错代码

python 复制代码
   raise RuntimeError(unbound_message) from None
RuntimeError: Working outside of application context.

This typically means that you attempted to use functionality that needed
the current application. To solve this, set up an application context
with app.app_context(). See the documentation for more information.

解决办法 :

1.创建 create.py文件

为了方便快速使用此代码,我把create.py非核心代码已注释掉,如下:

python 复制代码
from flask import Flask, json

# from utils.cache_helper import CacheHelper
# from utils.log_handler import LogHandler


def create_app():
    # init app
    app = Flask(__name__)
    # # 读取json配置
    # app.config.from_file("settings.json", load=json.load)
    # # 初始化Cache
    # cache = CacheHelper(app, config={'CACHE_TYPE': 'simple'})
    # # 添加日志配置
    # for log_handler in LogHandler.get_log_handlers():
    #     app.logger.addHandler(log_handler)
    return app

2.定时任务调用的方法中代码如下

引入create.py文件中create_app()方法
python 复制代码
from create import create_app
方法一
python 复制代码
   @classmethod
    def my_job(cls):
        # 此方法在定时任务多的情况下,会有性能问题,少的情况没啥问题
        app = create_app()
        with app.app_context():
            current_app.logger.info("my_job已执行")
            print(f"my_job,当前时间{datetime.now()}")
方法二 (推荐)

添加APP全局变量

python 复制代码
from create import create_app

APP = None


def get_app():
    global APP
    APP = APP if APP is not None else create_app()

定时任务调用的方法中使用如下

提示with APP.app_context():不要写成with APP.app_context: 会报错,因为app_context是一个方法而不是一个属性,所以要写成app_context(),加上括号

python 复制代码
 @classmethod
    def my_job(cls):      
        # 使用全局APP变量
        get_app()
        with APP.app_context():
            current_app.logger.info("my_job已执行")
            print(f"my_job,当前时间{datetime.now()}")

3.执行效果

总结:

flask定时任务(APScheduler)的使用,链接如下: https://blog.csdn.net/weixin_41934979/article/details/140245835

结合上边链接,就是完整的flask 定时任务(APScheduler)使用current_app的全过程和步骤

源代码地址:https://gitee.com/jxzcode_admin/flask-project.git

参考资料:

https://blog.csdn.net/weixin_42185136/article/details/104496351?spm=1001.2014.3001.5506

https://www.jianshu.com/p/d5a46b2d2fd3

相关推荐
J2K4 分钟前
JDK都25了,你还没用过ZGC?那真得补补课了
java·jvm·后端
EMQX4 分钟前
ESP32 + MCP over MQTT:通过大模型控制智能硬件设备
后端·mcp
郭京京6 分钟前
go框架gin(中)
后端·go
郭京京6 分钟前
go框架gin(下)
后端·go
林树的编程频道7 分钟前
单例模式的推导
后端
就是帅我不改9 分钟前
揭秘Netty高性能HTTP客户端:NIO编程的艺术与实践
后端·面试·github
Ray6612 分钟前
SugLucene索引构建
后端
舒一笑39 分钟前
Saga分布式事务框架执行逻辑
后端·程序员·设计
Emma歌小白1 小时前
完整后台模块模板
后端
得物技术1 小时前
MySQL单表为何别超2000万行?揭秘B+树与16KB页的生死博弈|得物技术
数据库·后端·mysql