在 asyncio 任务中添加时 call_next(request) 不起作用

问题描述

我设置了 Nginx 作为代理和 FastAPI 上游服务器。上传文件时,连接超时并抛出 Bad Gateway 错误。为了解决这个问题,我写了一个 keep-alive 中间件,它会一直发送空字符串作为响应,直到请求完成。请求完成后,我发送了实际响应。下面是相同的代码(非工作)。不起作用的部分是 call_next(request)。我收到一个多部分解码器错误 没有在索引 2 处找到带有当前代码的边界字符 130。如果我将 call_next(request) 放在中间件的 call 方法中,那么它可以正常工作,但是我将无法流式传输空白数据以保持连接有效。

有人能指出为什么会出现这个问题以及可能的解决方法吗?

class KeepAliveMiddleware: 

    @staticmethod
    async def slow_method():
        await asyncio.sleep(0.01)
        return "done slow"

    @staticmethod
    def send_blank(future):
        while not future.done():
            yield ""
        yield future.result()

    @staticmethod
    async def long_running_job(request,call_next):
        try:
            # await KeepAliveMiddleware.slow_method()  # This works fine
            return await call_next(request) # This leads to the error mentioned above.
        except Exception as ae:
            print(ae)

    async def __call__(self,request: Request,call_next):
        try:
            future = asyncio.create_task(
                KeepAliveMiddleware.long_running_job(request,call_next)
            )
            return StreamingResponse(KeepAliveMiddleware.send_blank(future))

        except Exception as e:
            print("Exception in task... ",e)


keep_alive_middleware = KeepAliveMiddleware()   
app.middleware("http")(keep_alive_middleware)

 

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...