如何解决在 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 举报,一经查实,本站将立刻删除。