RQ 作业的 Flask 上下文运行时错误:在应用程序之外工作

问题描述

首先,关于flask_context 的问题,包括RQ 作业的上下文似乎是常见问题,但我搜索了很多,仍然无法解决我的问题。

我的装饰器函数(在不同的变体中尝试了它们):

def redis_decorator1(f):
    def inner_wrapper(*args,**kwargs):
        # db interactions
        return res
    return inner_wrapper

def redis_decorator2(app):
    # app.app_context().push()
    def wrapper(f):
        def inner_wrapper(*args,**kwargs):
            # db interactions
            return res
        return inner_wrapper
    return wrapper



...
@redis_decorator
def under_decorator_func(*some_args)

函数 under_decorator_func 中使用 flask.current_app

问题:

First decorator -  RuntimeError: "Working outside of application
context" when redis task starts.

Second decorator - Same error on app start

我还在应用创建后立即尝试了 app.app_context().push(),所以我不知道这里发生了什么。

解决方法

结果证明解决方案非常明显,需要更多关于 Python 上下文的知识:

app = create_app() # or anything that creates your Flask application

...


def redis_decorator2(app):
def wrapper(f):
    def inner_wrapper(*args,**kwargs):
        with app.app_context():
            # db interactions
            return res
    return inner_wrapper
return wrapper

这里重要的是在 inner_wrapper 函数中使用烧瓶上下文而不是上面的任何层,否则你会得到和以前一样的错误。 希望它会帮助某人。