Skip to content

Commit

Permalink
add: new sample(3catchall) to describe how to cache all requests by f…
Browse files Browse the repository at this point in the history
…astapi.
  • Loading branch information
itaru2622 committed Apr 4, 2024
1 parent 97610fb commit 1df39bb
Show file tree
Hide file tree
Showing 5 changed files with 33 additions and 0 deletions.
1 change: 1 addition & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ RUN pip3 install -U setuptools pip; \
pip3 install fastapi[standard] uvicorn watchfiles requests bs4 Jinja2 q yq pytest pytest-cov httpx
RUN mkdir -p /app; echo "set mouse-=a" > /root/.vimrc;
COPY ./start.sh /usr/local/bin/start.sh
COPY ./samples /opt/fastapi-samples
WORKDIR /app
ENV py_requirements=./requirements.txt
ENV apt_requirements=./requirements-apt.txt
Expand Down
1 change: 1 addition & 0 deletions samples/3catchall/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
this folder shows sample to handle any path and method including websocket.
Empty file added samples/3catchall/__init__.py
Empty file.
30 changes: 30 additions & 0 deletions samples/3catchall/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# cf. https://stackoverflow.com/questions/63069190/how-to-capture-arbitrary-paths-at-one-route-in-fastapi

from fastapi import FastAPI, Request, WebSocket
import json

app = FastAPI()

@app.get ("/{full_path:path}")
@app.put ("/{full_path:path}")
@app.post ("/{full_path:path}")
@app.delete ("/{full_path:path}")
@app.options("/{full_path:path}")
@app.patch ("/{full_path:path}")
@app.trace ("/{full_path:path}")
async def catch_all(req: Request, full_path: str):
body = await req.body() or '{}'
body = json.loads(body)

# print( {"path" : full_path, "headers": req._headers, "query": req._query_params.items(), "reqScope": dict(req.scope) })
rtn ={ "method": req.scope.get("method"), "url": req.url._url, "query": dict(req._query_params), "body": body, "Authorization": req._headers.get('Authorization'), "host" : req._headers.get('host') }
print(rtn)
return rtn

@app.websocket("/{full_path:path}")
async def catch_websocket(ws:WebSocket, full_path: str):
await ws.accept()
await ws.send_text(f'recieve connection at: {full_path}')
while True:
msg = await ws.receive_text()
await ws.send_text(f'got: {msg}')
1 change: 1 addition & 0 deletions samples/3catchall/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
websockets

0 comments on commit 1df39bb

Please sign in to comment.