一个APP动态代理N个服务器 #35
Replies: 1 comment 2 replies
-
Hi @shizheng163 一个fastapi实现类似nginx那种同一个app里的路由代理到不同的服务器支持,参考这部分文档 from contextlib import asynccontextmanager
from typing import AsyncIterator
from fastapi import FastAPI
from fastapi_proxy_lib.core.http import ReverseHttpProxy
from httpx import AsyncClient
from starlette.requests import Request
user_proxy = ReverseHttpProxy(AsyncClient(), base_url="http://www.user-server.com/")
task_proxy = ReverseHttpProxy(AsyncClient(), base_url="http://www.task-server.com/")
@asynccontextmanager
async def close_proxy_event(_: FastAPI) -> AsyncIterator[None]:
"""Close proxy."""
yield
await user_proxy.aclose()
await task_proxy.aclose()
app = FastAPI(lifespan=close_proxy_event)
@app.get("/api/users/{path:path}")
async def _(request: Request):
return await user_proxy.proxy(request=request)
@app.get("/api/tasks/{path:path}")
async def _(request: Request):
return await task_proxy.proxy(request=request) 根据请求启动服务器,并提供反向代理如何启动服务器取决于你的实现,这个库没法帮你实现启动服务器的功能。 但是你可以在服务器启动后,动态创建一个proxy实例,proxy根本不在乎被挂载到哪个路由下,他只需要 这是我最近发现的一个下游用例,你可以参考下: 同时支持代理http和ws可以的,你在http路由那边挂一个http代理,然后在同路径下的ws路由那边再挂一个ws代理即可,只不过 参考上面提到的文档,你可以这样做: |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
您好,这个工具库支持这几种种场景吗?
时间比较匆忙,未能仔细阅读您的源码就提出问题,希望理解。
1. 一个fastapi实现类似nginx那种同一个app里的路由代理到不同的服务器。
例如
2. 根据请求启动服务器,并提供反向代理
3. 同时支持代理http和ws
一个fastapi的app同时支持http和ws
2024年04月11日10:28:38更新
ForwardHttpProxy 好像可以解决动态代理HTTP请求的需求
但是websocket转发似乎不可以?
Beta Was this translation helpful? Give feedback.
All reactions