Skip to content

Commit

Permalink
Fix #1788 incorrect url_for for routes with hosts, added tests. (#1789)
Browse files Browse the repository at this point in the history
* Fix #1788 incorrect url_for for routes with hosts, added tests.

* Linter

* Remove debug print
  • Loading branch information
Tronic authored Feb 21, 2020
1 parent 91f6aba commit 861e873
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 1 deletion.
10 changes: 9 additions & 1 deletion sanic/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -830,6 +830,14 @@ def url_for(self, view_name: str, **kwargs):
"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
Expand Down Expand Up @@ -862,7 +870,7 @@ def url_for(self, view_name: str, **kwargs):

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:
Expand Down
12 changes: 12 additions & 0 deletions tests/test_url_for.py
Original file line number Diff line number Diff line change
@@ -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"

0 comments on commit 861e873

Please sign in to comment.