From 861e87347a2d373d6ffa387965a6887c83af632c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?L=2E=20K=C3=A4rkk=C3=A4inen?= <98187+Tronic@users.noreply.github.com> Date: Fri, 21 Feb 2020 19:10:22 +0200 Subject: [PATCH] Fix #1788 incorrect url_for for routes with hosts, added tests. (#1789) * Fix #1788 incorrect url_for for routes with hosts, added tests. * Linter * Remove debug print --- sanic/app.py | 10 +++++++++- tests/test_url_for.py | 12 ++++++++++++ 2 files changed, 21 insertions(+), 1 deletion(-) create mode 100644 tests/test_url_for.py diff --git a/sanic/app.py b/sanic/app.py index abdd36fb..d12dc59b 100644 --- a/sanic/app.py +++ b/sanic/app.py @@ -830,6 +830,14 @@ class Sanic: "Endpoint with name `{}` was not found".format(view_name) ) + # If the route has host defined, split that off + # TODO: Retain netloc and path separately in Route objects + host = uri.find("/") + if host > 0: + host, uri = uri[:host], uri[host:] + else: + host = None + if view_name == "static" or view_name.endswith(".static"): filename = kwargs.pop("filename", None) # it's static folder @@ -862,7 +870,7 @@ class Sanic: netloc = kwargs.pop("_server", None) if netloc is None and external: - netloc = self.config.get("SERVER_NAME", "") + netloc = host or self.config.get("SERVER_NAME", "") if external: if not scheme: diff --git a/tests/test_url_for.py b/tests/test_url_for.py new file mode 100644 index 00000000..c7e51af1 --- /dev/null +++ b/tests/test_url_for.py @@ -0,0 +1,12 @@ +def test_routes_with_host(app): + @app.route("/") + @app.route("/", name="hostindex", host="example.com") + @app.route("/path", name="hostpath", host="path.example.com") + def index(request): + pass + + assert app.url_for("index") == "/" + assert app.url_for("hostindex") == "/" + assert app.url_for("hostpath") == "/path" + assert app.url_for("hostindex", _external=True) == "http://example.com/" + assert app.url_for("hostpath", _external=True) == "http://path.example.com/path"