FlaskThread


发布于

|

分类

遇到一个奇葩需求:某个API的回调,需要业务方在1s内返回200结果。但是我们的处理非常重,5分钟都不一定能处理完毕。这时候需要先返回一个假的200 response,再将实际的处理过程放在单独的线程里面慢慢做。

这里一个重点是获取app context,或者说current app。Google找到了解决办法,有两个实现。第一个实现是StackOverflow版本的,一直会有问题;第二个实现是GitHub里面 flask-threads 包,感觉不错。

from threading import Thread

from flask import _app_ctx_stack
from flask import has_app_context

class FlaskThread(Thread):
    """Implements Thread with flask AppContext."""

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        if not has_app_context():
            raise RuntimeError('Running outside of Flask AppContext.')
        self.app_ctx = _app_ctx_stack.top

    def run(self):
        try:
            self.app_ctx.push()
            super().run()
        finally:
            self.app_ctx.pop()

嗯,就这样~


评论

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注