--cors for /name.db downloads, refs #1057

This commit is contained in:
Simon Willison 2020-10-27 13:39:07 -07:00
commit 677e040979
4 changed files with 19 additions and 5 deletions

View file

@ -247,9 +247,9 @@ async def asgi_start(send, status, headers=None, content_type="text/plain"):
async def asgi_send_file( async def asgi_send_file(
send, filepath, filename=None, content_type=None, chunk_size=4096 send, filepath, filename=None, content_type=None, chunk_size=4096, headers=None
): ):
headers = {} headers = headers or {}
if filename: if filename:
headers["content-disposition"] = 'attachment; filename="{}"'.format(filename) headers["content-disposition"] = 'attachment; filename="{}"'.format(filename)
first = True first = True
@ -395,13 +395,22 @@ class Response:
class AsgiFileDownload: class AsgiFileDownload:
def __init__( def __init__(
self, filepath, filename=None, content_type="application/octet-stream" self,
filepath,
filename=None,
content_type="application/octet-stream",
headers=None,
): ):
self.headers = headers or {}
self.filepath = filepath self.filepath = filepath
self.filename = filename self.filename = filename
self.content_type = content_type self.content_type = content_type
async def asgi_send(self, send): async def asgi_send(self, send):
return await asgi_send_file( return await asgi_send_file(
send, self.filepath, filename=self.filename, content_type=self.content_type send,
self.filepath,
filename=self.filename,
content_type=self.content_type,
headers=self.headers,
) )

View file

@ -144,10 +144,14 @@ class DatabaseDownload(DataView):
if not db.path: if not db.path:
raise DatasetteError("Cannot download database", status=404) raise DatasetteError("Cannot download database", status=404)
filepath = db.path filepath = db.path
headers = {}
if self.ds.cors:
headers["Access-Control-Allow-Origin"] = "*"
return AsgiFileDownload( return AsgiFileDownload(
filepath, filepath,
filename=os.path.basename(filepath), filename=os.path.basename(filepath),
content_type="application/octet-stream", content_type="application/octet-stream",
headers=headers,
) )

View file

@ -227,7 +227,7 @@ def app_client_with_dot():
@pytest.fixture(scope="session") @pytest.fixture(scope="session")
def app_client_with_cors(): def app_client_with_cors():
with make_app_client(cors=True) as client: with make_app_client(is_immutable=True, cors=True) as client:
yield client yield client

View file

@ -1739,6 +1739,7 @@ def test_trace(app_client):
@pytest.mark.parametrize( @pytest.mark.parametrize(
"path,status_code", "path,status_code",
[ [
("/fixtures.db", 200),
("/fixtures.json", 200), ("/fixtures.json", 200),
("/fixtures/no_primary_key.json", 200), ("/fixtures/no_primary_key.json", 200),
# A 400 invalid SQL query should still have the header: # A 400 invalid SQL query should still have the header: