base_url configuration setting, closes #394

* base_url configuration setting
* base_url works for static assets as well
This commit is contained in:
Simon Willison 2020-03-24 17:18:43 -07:00 committed by GitHub
commit 7656fd64d8
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
15 changed files with 104 additions and 28 deletions

View file

@ -135,7 +135,9 @@ CONFIG_OPTIONS = (
False,
"Allow display of template debug information with ?_context=1",
),
ConfigOption("base_url", "/", "Datasette URLs should use this base"),
)
DEFAULT_CONFIG = {option.name: option.default for option in CONFIG_OPTIONS}
@ -573,6 +575,7 @@ class Datasette:
"format_bytes": format_bytes,
"extra_css_urls": self._asset_urls("extra_css_urls", template, context),
"extra_js_urls": self._asset_urls("extra_js_urls", template, context),
"base_url": self.config("base_url"),
},
**extra_template_vars,
}
@ -736,6 +739,13 @@ class DatasetteRouter(AsgiRouter):
self.ds = datasette
super().__init__(routes)
async def route_path(self, scope, receive, send, path):
# Strip off base_url if present before routing
base_url = self.ds.config("base_url")
if base_url != "/" and path.startswith(base_url):
path = "/" + path[len(base_url) :]
return await super().route_path(scope, receive, send, path)
async def handle_404(self, scope, receive, send):
# If URL has a trailing slash, redirect to URL without it
path = scope.get("raw_path", scope["path"].encode("utf8"))