
fastapi中将中间件改为同步模式
在fastapi中,中间件通常是异步的,但这会带来一些 inconveniente,尤其是在使用不兼容异步的库时。因此,对于希望将中间件函数保持为同步的情况,可以考虑以下解决方案:
使用run_in_threadpool执行同步代码
第一步】:将安装包中所有的文件夹和文件用ftp工具以二进制方式上传至服务器空间;(如果您不知如何设置ftp工具的二进制方式,可以查看:(http://www.shopex.cn/support/qa/setup.help.717.html)【第二步】:在浏览器中输入 http://您的商店域名/install 进行安装界面进行安装即可。【第二步】:登录后台,工具箱里恢复数据管理后台是url/sho
run_in_threadpool是一个辅助函数,允许在后台线程池中运行同步代码。我们可以使用它来将同步代码包装在异步函数中,如下所示:
from fastapi import FastAPI, Request, Response
from starlette.concurrency import run_in_threadpool
app = FastAPI()
def sync_code():
# 这里放你的同步代码
pass
@app.middleware("http")
async def sync_middleware(request: Request, call_next):
await run_in_threadpool(sync_code)
response = await call_next(request)
return response在这种方法中,sync_code函数包含你的同步代码。run_in_threadpool将其包装在一个异步函数中,允许它在后台线程池中运行。这样,你就可以在中间件中使用同步代码,同时保持其异步性质。









