-
Couldn't load subscription status.
- Fork 9
一个APP动态代理N个服务器 #35
-
您好,这个工具库支持这几种种场景吗?
时间比较匆忙,未能仔细阅读您的源码就提出问题,希望理解。
1. 一个fastapi实现类似nginx那种同一个app里的路由代理到不同的服务器。
例如
- /api/users/ -> 代理到用户服务器
- /api/tasks/ -> 代理到任务服务器
2. 根据请求启动服务器,并提供反向代理
- /api/viewers/1/start 启动一个viewer服务器
- /viewers/1/ -> 代理到上一步启动的服务器
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
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根本不在乎被挂载到哪个路由下,他只需要request或者websocket参数即可。
这是我最近发现的一个下游用例,你可以参考下:
https://github.com/dbmi-pitt/hades_proxy_manager/blob/d931c14b7048d11bc7ff7cea4a1df1b457fe4fcf/src/routers/auth.py#L55-L59
https://github.com/dbmi-pitt/hades_proxy_manager/blob/d931c14b7048d11bc7ff7cea4a1df1b457fe4fcf/src/routers/proxy.py#L10-L35
同时支持代理http和ws
可以的,你在http路由那边挂一个http代理,然后在同路径下的ws路由那边再挂一个ws代理即可,只不过fastapi_proxy_lib.fastapi.app里的便捷函数没有实现这个功能而已。
参考上面提到的文档,你可以这样做:
https://github.com/WSH032/aria2-server-gui/blob/80dfe89e8a3511cfdc75071bfc76b0d0f777328c/src/aria2_server/app/server/_core/_api/_aria2.py#L86-L94
Beta Was this translation helpful? Give feedback.
All reactions
-
非常感谢,很荣幸和你交流。
可以加个微信吗,我的微信:13621215534 期待你的申请
Beta Was this translation helpful? Give feedback.
All reactions
-
就在Github上交流呗,这样其他人也能看得见,也能帮助大家。
Beta Was this translation helpful? Give feedback.