Experimental path_from_header feature, refs #712

This commit is contained in:
Simon Willison 2020-03-25 19:50:54 -07:00
commit fb0460dd0b
3 changed files with 19 additions and 0 deletions

View file

@ -136,6 +136,7 @@ CONFIG_OPTIONS = (
"Allow display of template debug information with ?_context=1", "Allow display of template debug information with ?_context=1",
), ),
ConfigOption("base_url", "/", "Datasette URLs should use this base"), ConfigOption("base_url", "/", "Datasette URLs should use this base"),
ConfigOption("path_from_header", "", "HTTP header to override incoming path"),
) )
DEFAULT_CONFIG = {option.name: option.default for option in CONFIG_OPTIONS} DEFAULT_CONFIG = {option.name: option.default for option in CONFIG_OPTIONS}
@ -739,6 +740,16 @@ class DatasetteRouter(AsgiRouter):
self.ds = datasette self.ds = datasette
super().__init__(routes) super().__init__(routes)
async def __call__(self, scope, receive, send):
path_from_header = self.ds.config("path_from_header")
path = scope["path"]
raw_path = scope.get("raw_path")
if path_from_header:
raw_path = dict(scope["headers"])[path_from_header.encode("utf8")]
if raw_path:
path = raw_path.decode("ascii")
return await self.route_path(scope, receive, send, path)
async def route_path(self, scope, receive, send, path): async def route_path(self, scope, receive, send, path):
# Strip off base_url if present before routing # Strip off base_url if present before routing
base_url = self.ds.config("base_url") base_url = self.ds.config("base_url")

View file

@ -241,3 +241,10 @@ For example, if you are sending traffic from ``https://www.example.com/tools/dat
You can do that like so:: You can do that like so::
datasette mydatabase.db --config base_url:/tools/datasette/ datasette mydatabase.db --config base_url:/tools/datasette/
.. _path_from_header:
path_from_header
----------------
See `issue #712 <https://github.com/simonw/datasette/issues/712>`__.

View file

@ -1308,6 +1308,7 @@ def test_config_json(app_client):
"hash_urls": False, "hash_urls": False,
"template_debug": False, "template_debug": False,
"base_url": "/", "base_url": "/",
"path_from_header": "",
} == response.json } == response.json