From 8d86c3c59893c3f83c7fe3c4afa3d5a6883938f1 Mon Sep 17 00:00:00 2001 From: laggardkernel Date: Mon, 15 Mar 2021 02:33:07 +0800 Subject: [PATCH] Remove unnecessary prefix from websocket handler name (#2021) Remove the websocket prefix "websocket_handler_" introduced in 761eef7. Add a backward support for url_for() calling with this prefix in param "view_name". --- sanic/app.py | 23 ++++++++++++++++++++--- tests/test_url_building.py | 10 ++++++++++ 2 files changed, 30 insertions(+), 3 deletions(-) diff --git a/sanic/app.py b/sanic/app.py index 7ddbbdbc..850e1fe3 100644 --- a/sanic/app.py +++ b/sanic/app.py @@ -12,6 +12,7 @@ from ssl import Purpose, SSLContext, create_default_context from traceback import format_exc from typing import Any, Dict, Optional, Type, Union from urllib.parse import urlencode, urlunparse +from warnings import warn from sanic import reloader_helpers from sanic.asgi import ASGIApp @@ -494,9 +495,7 @@ class Sanic: websocket_handler = partial( self._websocket_handler, handler, subprotocols=subprotocols ) - websocket_handler.__name__ = ( - "websocket_handler_" + handler.__name__ - ) + websocket_handler.__name__ = handler.__name__ routes.extend( self.router.add( uri=uri, @@ -747,6 +746,24 @@ class Sanic: kw.update(name=view_name) uri, route = self.router.find_route_by_view_name(view_name, **kw) + + # TODO(laggardkernel): this fix should be removed in v21.3. + # Try again without the unnecessary prefix "websocket_handler_", + # which was added by accident on non-blueprint handlers. GH-2021 + if not (uri and route) and view_name.startswith("websocket_handler_"): + view_name = view_name[18:] + uri, route = self.router.find_route_by_view_name(view_name, **kw) + if uri and route: + warn( + "The bug of adding unnecessary `websocket_handler_` " + "prefix in param `view_name` for non-blueprint handlers " + "is fixed. This backward support will be removed in " + "v21.3. Please update `Sanic.url_for()` callings in your " + "code soon.", + DeprecationWarning, + stacklevel=2, + ) + if not (uri and route): raise URLBuildError( f"Endpoint with name `{view_name}` was not found" diff --git a/tests/test_url_building.py b/tests/test_url_building.py index 81fb8aaa..e483cd1b 100644 --- a/tests/test_url_building.py +++ b/tests/test_url_building.py @@ -348,3 +348,13 @@ def test_methodview_naming(methodview_app): assert viewone_url == "/view_one" assert viewtwo_url == "/view_two" + + +def test_url_for_with_websocket_handlers(app): + # Test for a specific bugfix in GH-2021 + @app.websocket("/ws") + async def my_handler(request, ws): + pass + + assert app.url_for("my_handler") == "/ws" + assert app.url_for("websocket_handler_my_handler") == "/ws"