解决flask报错:RuntimeError: Working outside of application context.

11 篇文章 1 订阅

先看报错:
RuntimeError: Working outside of application context.

This typically means that you attempted to use functionality that
needed to interface with the current application object in some way.
To solve this, set up an application context with app.app_context().

RuntimeError (_app_ctx_err_msg): Working outside of application context while sending mail from thread

raise RuntimeError(_app_ctx_err_msg)

在flask中,前端发起请求起一个耗时的任务,后端处理逻辑不可能等待该任务执行完成再返回结果,那样前端会卡死,所以用线程去起那个耗时的任务,问题来了,该耗时任务结束后会报上下文错误,
在这里插入图片描述
解决方法如下:
在这里插入图片描述
其中current_app是通过 from flask import current_app导入, current_app._get_current_object()作为线程参数传递,然后在deal_ordertasks这个耗时任务中加上 with app.app_context():即可。

类似的,还有发送邮件也可以参考此方法
在这里插入图片描述
在这里插入图片描述
最后感谢分享的各位大神
https://stackoverflow.com/questions/55417236/runtimeerror-app-ctx-err-msg-working-outside-of-application-context-while-se

https://www.cnblogs.com/xiaxiaoxu/p/10753543.html

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值