Skip to content

Commit 11f9ff9

Browse files
committed
feat!: remove path parameter in proxy method
1 parent 326f8b0 commit 11f9ff9

File tree

4 files changed

+23
-46
lines changed

4 files changed

+23
-46
lines changed

src/fastapi_proxy_lib/core/http.py

Lines changed: 8 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -327,8 +327,8 @@ async def close_proxy_event(_: FastAPI) -> AsyncIterator[None]: # (1)!
327327
app = FastAPI(lifespan=close_proxy_event)
328328
329329
@app.get("/{path:path}") # (2)!
330-
async def _(request: Request, path: str = ""):
331-
return await proxy.proxy(request=request, path=path) # (3)!
330+
async def _(request: Request):
331+
return await proxy.proxy(request=request) # (3)!
332332
333333
# Then run shell: `uvicorn <your.py>:app --host http://127.0.0.1:8000 --port 8000`
334334
# visit the app: `http://127.0.0.1:8000/`
@@ -339,10 +339,6 @@ async def _(request: Request, path: str = ""):
339339
2. `{path:path}` is the key.<br>
340340
It allows the app to accept all path parameters.<br>
341341
visit <https://www.starlette.io/routing/#path-parameters> for more info.
342-
3. !!! info
343-
In fact, you only need to pass the `request: Request` argument.<br>
344-
`fastapi_proxy_lib` can automatically get the `path` from `request`.<br>
345-
Explicitly pointing it out here is just to remind you not to forget to specify `{path:path}`.
346342
'''
347343

348344
client: httpx.AsyncClient
@@ -376,25 +372,20 @@ def __init__(
376372

377373
@override
378374
async def proxy( # pyright: ignore [reportIncompatibleMethodOverride]
379-
self, *, request: StarletteRequest, path: Optional[str] = None
375+
self, *, request: StarletteRequest
380376
) -> StarletteResponse:
381377
"""Send request to target server.
382378
383379
Args:
384380
request: `starlette.requests.Request`
385-
path: The path params of request, which means the path params of base url.<br>
386-
If None, will get it from `request.path_params`.<br>
387-
**Usually, you don't need to pass this argument**.
388381
389382
Returns:
390383
The response from target server.
391384
"""
392385
base_url = self.base_url
393386

394387
# 只取第一个路径参数。注意,我们允许没有路径参数,这代表直接请求
395-
path_param: str = (
396-
path if path is not None else next(iter(request.path_params.values()), "")
397-
)
388+
path_param: str = next(iter(request.path_params.values()), "")
398389

399390
# 将路径参数拼接到目标url上
400391
# e.g: "https://www.example.com/p0/" + "p1"
@@ -462,8 +453,8 @@ async def close_proxy_event(_: FastAPI) -> AsyncIterator[None]:
462453
app = FastAPI(lifespan=close_proxy_event)
463454
464455
@app.get("/{path:path}")
465-
async def _(request: Request, path: str = ""):
466-
return await proxy.proxy(request=request, path=path)
456+
async def _(request: Request):
457+
return await proxy.proxy(request=request)
467458
468459
# Then run shell: `uvicorn <your.py>:app --host http://127.0.0.1:8000 --port 8000`
469460
# visit the app: `http://127.0.0.1:8000/http://www.example.com`
@@ -502,25 +493,20 @@ async def proxy( # pyright: ignore [reportIncompatibleMethodOverride]
502493
self,
503494
*,
504495
request: StarletteRequest,
505-
path: Optional[str] = None,
506496
) -> StarletteResponse:
507497
"""Send request to target server.
508498
509499
Args:
510500
request: `starlette.requests.Request`
511-
path: The path params of request, which means the full url of target server.<br>
512-
If None, will get it from `request.path_params`.<br>
513-
**Usually, you don't need to pass this argument**.
514501
515502
Returns:
516503
The response from target server.
517504
"""
518505
proxy_filter = self.proxy_filter
519506

520507
# 只取第一个路径参数
521-
path_param: str = (
522-
next(iter(request.path_params.values()), "") if path is None else path
523-
)
508+
path_param: str = next(iter(request.path_params.values()), "")
509+
524510
# 如果没有路径参数,即在正向代理中未指定目标url,则返回400
525511
if path_param == "":
526512
error = _BadTargetUrlError("Must provide target url.")

src/fastapi_proxy_lib/core/websocket.py

Lines changed: 4 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -671,8 +671,8 @@ async def close_proxy_event(_: FastAPI) -> AsyncIterator[None]:
671671
app = FastAPI(lifespan=close_proxy_event)
672672
673673
@app.websocket("/{path:path}")
674-
async def _(websocket: WebSocket, path: str = ""):
675-
return await proxy.proxy(websocket=websocket, path=path)
674+
async def _(websocket: WebSocket):
675+
return await proxy.proxy(websocket=websocket)
676676
677677
# Then run shell: `uvicorn <your.py>:app --host http://127.0.0.1:8000 --port 8000`
678678
# visit the app: `ws://127.0.0.1:8000/`
@@ -737,15 +737,12 @@ def __init__(
737737

738738
@override
739739
async def proxy( # pyright: ignore [reportIncompatibleMethodOverride]
740-
self, *, websocket: starlette_ws.WebSocket, path: Optional[str] = None
740+
self, *, websocket: starlette_ws.WebSocket
741741
) -> Union[Literal[False], StarletteResponse]:
742742
"""Establish websocket connection for both client and target_url, then pass messages between them.
743743
744744
Args:
745745
websocket: The client websocket requests.
746-
path: The path params of websocket request, which means the path params of base url.<br>
747-
If None, will get it from `websocket.path_params`.<br>
748-
**Usually, you don't need to pass this argument**.
749746
750747
Returns:
751748
If the establish websocket connection unsuccessfully:
@@ -757,9 +754,7 @@ async def proxy( # pyright: ignore [reportIncompatibleMethodOverride]
757754
base_url = self.base_url
758755

759756
# 只取第一个路径参数。注意,我们允许没有路径参数,这代表直接请求
760-
path_param: str = (
761-
path if path is not None else next(iter(websocket.path_params.values()), "")
762-
)
757+
path_param: str = next(iter(websocket.path_params.values()), "")
763758

764759
# 将路径参数拼接到目标url上
765760
# e.g: "https://www.example.com/p0/" + "p1"

src/fastapi_proxy_lib/fastapi/router.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,7 @@ def _http_register_router(
6363
@router.patch("/{path:path}", **kwargs)
6464
@router.trace("/{path:path}", **kwargs)
6565
async def http_proxy( # pyright: ignore[reportUnusedFunction]
66-
request: Request, path: str = ""
66+
request: Request,
6767
) -> Response:
6868
"""HTTP proxy endpoint.
6969
@@ -74,7 +74,7 @@ async def http_proxy( # pyright: ignore[reportUnusedFunction]
7474
Returns:
7575
The response from target server.
7676
"""
77-
return await proxy.proxy(request=request, path=path)
77+
return await proxy.proxy(request=request)
7878

7979

8080
def _ws_register_router(
@@ -96,7 +96,7 @@ def _ws_register_router(
9696

9797
@router.websocket("/{path:path}", **kwargs)
9898
async def ws_proxy( # pyright: ignore[reportUnusedFunction]
99-
websocket: WebSocket, path: str = ""
99+
websocket: WebSocket,
100100
) -> Union[Response, Literal[False]]:
101101
"""WebSocket proxy endpoint.
102102
@@ -111,7 +111,7 @@ async def ws_proxy( # pyright: ignore[reportUnusedFunction]
111111
If the establish websocket connection successfully:
112112
- Will run forever until the connection is closed. Then return False.
113113
"""
114-
return await proxy.proxy(websocket=websocket, path=path)
114+
return await proxy.proxy(websocket=websocket)
115115

116116

117117
class RouterHelper:

tests/test_docs_examples.py

Lines changed: 7 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -23,8 +23,8 @@ async def close_proxy_event(_: FastAPI) -> AsyncIterator[None]:
2323
app = FastAPI(lifespan=close_proxy_event)
2424

2525
@app.get("/{path:path}")
26-
async def _(request: Request, path: str = ""):
27-
return await proxy.proxy(request=request, path=path)
26+
async def _(request: Request):
27+
return await proxy.proxy(request=request)
2828

2929
# Then run shell: `uvicorn <your.py>:app --host http://127.0.0.1:8000 --port 8000`
3030
# visit the app: `http://127.0.0.1:8000/http://www.example.com`
@@ -52,8 +52,8 @@ async def close_proxy_event(_: FastAPI) -> AsyncIterator[None]: # (1)!
5252
app = FastAPI(lifespan=close_proxy_event)
5353

5454
@app.get("/{path:path}") # (2)!
55-
async def _(request: Request, path: str = ""):
56-
return await proxy.proxy(request=request, path=path) # (3)!
55+
async def _(request: Request):
56+
return await proxy.proxy(request=request) # (3)!
5757

5858
# Then run shell: `uvicorn <your.py>:app --host http://127.0.0.1:8000 --port 8000`
5959
# visit the app: `http://127.0.0.1:8000/`
@@ -62,11 +62,7 @@ async def _(request: Request, path: str = ""):
6262
""" 1. lifespan please refer to [starlette/lifespan](https://www.starlette.io/lifespan/)
6363
2. `{path:path}` is the key.<br>
6464
It allows the app to accept all path parameters.<br>
65-
visit <https://www.starlette.io/routing/#path-parameters> for more info.
66-
3. !!! info
67-
In fact, you only need to pass the `request: Request` argument.<br>
68-
`fastapi_proxy_lib` can automatically get the `path` from `request`.<br>
69-
Explicitly pointing it out here is just to remind you not to forget to specify `{path:path}`. """
65+
visit <https://www.starlette.io/routing/#path-parameters> for more info. """
7066

7167

7268
def test_reverse_ws_proxy() -> None:
@@ -90,8 +86,8 @@ async def close_proxy_event(_: FastAPI) -> AsyncIterator[None]:
9086
app = FastAPI(lifespan=close_proxy_event)
9187

9288
@app.websocket("/{path:path}")
93-
async def _(websocket: WebSocket, path: str = ""):
94-
return await proxy.proxy(websocket=websocket, path=path)
89+
async def _(websocket: WebSocket):
90+
return await proxy.proxy(websocket=websocket)
9591

9692
# Then run shell: `uvicorn <your.py>:app --host http://127.0.0.1:8000 --port 8000`
9793
# visit the app: `ws://127.0.0.1:8000/`

0 commit comments

Comments
 (0)