Skip to content

Commit

Permalink
--cors for /name.db downloads, refs #1057
Browse files Browse the repository at this point in the history
  • Loading branch information
simonw committed Oct 27, 2020
1 parent e5f5034 commit c3aba4a
Show file tree
Hide file tree
Showing 4 changed files with 19 additions and 5 deletions.
17 changes: 13 additions & 4 deletions datasette/utils/asgi.py
Original file line number Diff line number Diff line change
Expand Up @@ -247,9 +247,9 @@ async def asgi_start(send, status, headers=None, content_type="text/plain"):


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:
headers["content-disposition"] = 'attachment; filename="{}"'.format(filename)
first = True
Expand Down Expand Up @@ -395,13 +395,22 @@ def redirect(cls, path, status=302, headers=None):

class AsgiFileDownload:
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.filename = filename
self.content_type = content_type

async def asgi_send(self, send):
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,
)
4 changes: 4 additions & 0 deletions datasette/views/database.py
Original file line number Diff line number Diff line change
Expand Up @@ -144,10 +144,14 @@ async def view_get(self, request, database, hash, correct_hash_present, **kwargs
if not db.path:
raise DatasetteError("Cannot download database", status=404)
filepath = db.path
headers = {}
if self.ds.cors:
headers["Access-Control-Allow-Origin"] = "*"
return AsgiFileDownload(
filepath,
filename=os.path.basename(filepath),
content_type="application/octet-stream",
headers=headers,
)


Expand Down
2 changes: 1 addition & 1 deletion tests/fixtures.py
Original file line number Diff line number Diff line change
Expand Up @@ -227,7 +227,7 @@ def app_client_with_dot():

@pytest.fixture(scope="session")
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


Expand Down
1 change: 1 addition & 0 deletions tests/test_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -1739,6 +1739,7 @@ def test_trace(app_client):
@pytest.mark.parametrize(
"path,status_code",
[
("/fixtures.db", 200),
("/fixtures.json", 200),
("/fixtures/no_primary_key.json", 200),
# A 400 invalid SQL query should still have the header:
Expand Down

0 comments on commit c3aba4a

Please sign in to comment.