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
This commit is contained in:
L. Kärkkäinen 2020-02-21 19:10:22 +02:00 committed by GitHub
parent 91f6abaa81
commit 861e87347a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 21 additions and 1 deletions

View File

@ -830,6 +830,14 @@ class Sanic:
"Endpoint with name `{}` was not found".format(view_name) "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"): if view_name == "static" or view_name.endswith(".static"):
filename = kwargs.pop("filename", None) filename = kwargs.pop("filename", None)
# it's static folder # it's static folder
@ -862,7 +870,7 @@ class Sanic:
netloc = kwargs.pop("_server", None) netloc = kwargs.pop("_server", None)
if netloc is None and external: if netloc is None and external:
netloc = self.config.get("SERVER_NAME", "") netloc = host or self.config.get("SERVER_NAME", "")
if external: if external:
if not scheme: if not scheme:

12
tests/test_url_for.py Normal file
View File

@ -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"