问题描述
我设置了 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 (将#修改为@)