DatasetteRouter is no longer a nested class

This commit is contained in:
Simon Willison 2019-06-23 16:02:33 -07:00
commit 176dd4f12a

View file

@ -645,9 +645,22 @@ class Datasette:
) )
self.register_custom_units() self.register_custom_units()
outer_self = self async def setup_db():
# First time server starts up, calculate table counts for immutable databases
for dbname, database in self.databases.items():
if not database.is_mutable:
await database.table_counts(limit=60 * 60 * 1000)
return AsgiLifespan(
AsgiTracer(DatasetteRouter(self, routes)), on_startup=setup_db
)
class DatasetteRouter(AsgiRouter): class DatasetteRouter(AsgiRouter):
def __init__(self, datasette, routes):
self.ds = datasette
super().__init__(routes)
async def handle_404(self, scope, receive, send): async def handle_404(self, scope, receive, send):
# If URL has a trailing slash, redirect to URL without it # If URL has a trailing slash, redirect to URL without it
path = scope.get("raw_path", scope["path"].encode("utf8")) path = scope.get("raw_path", scope["path"].encode("utf8"))
@ -680,24 +693,14 @@ class Datasette:
templates = ["500.html"] templates = ["500.html"]
if status != 500: if status != 500:
templates = ["{}.html".format(status)] + templates templates = ["{}.html".format(status)] + templates
info.update( info.update({"ok": False, "error": message, "status": status, "title": title})
{"ok": False, "error": message, "status": status, "title": title}
)
headers = {} headers = {}
if outer_self.cors: if self.ds.cors:
headers["Access-Control-Allow-Origin"] = "*" headers["Access-Control-Allow-Origin"] = "*"
if scope["path"].split("?")[0].endswith(".json"): if scope["path"].split("?")[0].endswith(".json"):
await asgi_send_json(send, info, status=status, headers=headers) await asgi_send_json(send, info, status=status, headers=headers)
else: else:
template = outer_self.jinja_env.select_template(templates) template = self.ds.jinja_env.select_template(templates)
await asgi_send_html( await asgi_send_html(
send, template.render(info), status=status, headers=headers send, template.render(info), status=status, headers=headers
) )
async def setup_db():
# First time server starts up, calculate table counts for immutable databases
for dbname, database in self.databases.items():
if not database.is_mutable:
await database.table_counts(limit=60 * 60 * 1000)
return AsgiLifespan(AsgiTracer(DatasetteRouter(routes)), on_startup=setup_db)