Skip to content

Commit

Permalink
Remove unnecessary prefix from websocket handler name (#2021)
Browse files Browse the repository at this point in the history
Remove the websocket prefix "websocket_handler_" introduced in
761eef7. Add a backward support for url_for() calling with this prefix
in param "view_name".
  • Loading branch information
laggardkernel authored Mar 14, 2021
1 parent 9763511 commit 8d86c3c
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 3 deletions.
23 changes: 20 additions & 3 deletions sanic/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
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
Expand Down Expand Up @@ -494,9 +495,7 @@ def response(handler):
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,
Expand Down Expand Up @@ -747,6 +746,24 @@ def url_for(self, view_name: str, **kwargs):
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"
Expand Down
10 changes: 10 additions & 0 deletions tests/test_url_building.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"

0 comments on commit 8d86c3c

Please sign in to comment.