没有后台对象时如何在Starlette中使用后台任务?

时间:2020-05-26 21:26:06

标签: starlette ariadne-graphql

我希望此刻避免使用芹菜。在Starlette的文档中,他们提供了两种添加后台任务的方法:

通过石墨烯:https://www.starlette.io/graphql/

class Query(graphene.ObjectType):
    user_agent = graphene.String()

    def resolve_user_agent(self, info):
        """
        Return the User-Agent of the incoming request.
        """
        user_agent = request.headers.get("User-Agent", "<unknown>")
        background = info.context["background"]
        background.add_task(log_user_agent, user_agent=user_agent)
        return user_agent

通过JSON响应:https://www.starlette.io/background/

async def signup(request):
    data = await request.json()
    username = data['username']
    email = data['email']
    task = BackgroundTask(send_welcome_email, to_address=email)
    message = {'status': 'Signup successful'}
    return JSONResponse(message, background=task)

有人知道使用Ariadne向Starlette的后台添加任务的方法吗?我无法在解析器中返回JSONResponse,并且无法访问info.context [“ background”]。我唯一附加到上下文中的是我的请求对象。

1 个答案:

答案 0 :(得分:0)

已解决!

Starlette中间件:

class BackgroundTaskMiddleware(BaseHTTPMiddleware):
    async def dispatch(
            self, request: Request, call_next: RequestResponseEndpoint
    ) -> Response:
        request.state.background = None
        response = await call_next(request)
        if request.state.background:
            response.background = request.state.background
        return response

Ariadne解析器:

@query.field("getUser")
@check_authentication
async def resolve_get_user(user, obj, info):
    task = BackgroundTasks()
    task.add_task(test_func)
    task.add_task(testing_func_two, "I work now")
    request = info.context["request"]
    request.state.background = task
    return True


async def test_func():
    await asyncio.sleep(10)
    print("once!!")


async def testing_func_two(message: str):
    print(message)

这些功能仍然可以同步执行,但是因为它们是后台任务,所以我不太担心。

More discussion here.