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

相关推荐
Asthenia04125 分钟前
一名实习生的复盘:技术与规划的经验教训
后端
失去妙妙屋的米奇5 分钟前
Python与图像处理
图像处理·python·计算机视觉
Asthenia041218 分钟前
从面试问题看端口连通性:Ping、TCP/UDP与业务实践
后端
yuanpan32 分钟前
如何将python项目打包成Windows环境的exe应用提供给客户使用
开发语言·windows·python
程序员一诺33 分钟前
【爬虫开发】爬虫开发从0到1全知识教程第14篇:scrapy爬虫框架,介绍【附代码文档】
后端·爬虫·python·数据
njsgcs43 分钟前
python getattr调用当前文件引用的模块内的方法,实例
开发语言·python
Asthenia04121 小时前
Spring事件机制:微服务架构下的子服务内部解耦合/多场景代码分析
后端
独好紫罗兰1 小时前
洛谷题单3-P2669 [NOIP 2015 普及组] 金币-python-流程图重构
开发语言·python·算法
Asthenia04121 小时前
面试官问我:Spring AOP的代理模式与实现原理深度剖析
后端
跳跳糖炒酸奶1 小时前
第四章、Isaacsim在GUI中构建机器人(3):添加摄像头和传感器
人工智能·python·算法·ubuntu·机器人