-
First Check
Commit to Help
Example Codeimport uvicorn
from fastapi import FastAPI, WebSocket
from fastapi.responses import RedirectResponse
from fastapi.datastructures import URL
from starlette.types import ASGIApp, Receive, Scope, Send
class WSRedirectMiddleware:
def __init__(
self,
app: ASGIApp,
redirect_paths: list
) -> None:
self.app = app
self.redirect_paths = redirect_paths
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
url = URL(scope=scope)
if scope["type"] == "websocket" and url.path in self.redirect_paths:
print(f'Got path: {url.path}')
url = f'{scope["scheme"]}://{url.hostname}:{url.port}/ws2'
print(f'Redirect to: {url}')
response = RedirectResponse(url, status_code=307)
await response(scope, receive, send)
else:
await self.app(scope, receive, send)
application = FastAPI()
# Redirect from /ws1 to /ws2
application.add_middleware(WSRedirectMiddleware, redirect_paths=['/ws1'])
@application.websocket("/ws1")
async def websocket(ws: WebSocket):
await ws.accept()
await ws.send_json({"msg": "Hello WebSocket1"})
await ws.close()
@application.websocket("/ws2")
async def websocket(ws: WebSocket):
await ws.accept()
await ws.send_json({"msg": "Hello WebSocket2"})
await ws.close()
if __name__ == '__main__':
uvicorn.run(application, host="localhost", port=8088) DescriptionHello all, Created an alternative of HTTPSRedirectMiddleware for redirection, but it's not working as I expected. Error logs:
Checking the FastAPI httpsredirect.py and various middleware-guides out there I thought this would work... but looking at the ASGI spec it seems impossible... Or can it be done? With best regards, /x-stride Operating SystemWindows Operating System DetailsNo response FastAPI Version0.85.0 Python Version3.10.11 Additional ContextNo response |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 3 replies
-
@tiangolo I would also be interested in that. My use case is the need to have an application with FastAPI serving the data and a Panel Server rendering graphs via Websockets, running on a different port. But I can expose only one port to the web and thus I would like a WebsocketRedirect from one route to the Panel Server. |
Beta Was this translation helpful? Give feedback.
-
I think the |
Beta Was this translation helpful? Give feedback.
I think the
HTTPSRedirectMiddleware
redirect works for WebSockets now.