Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow non latin-1 filename in FileResponse #792

Merged
merged 1 commit into from
Feb 17, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 8 additions & 2 deletions starlette/responses.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
import typing
from email.utils import formatdate
from mimetypes import guess_type
from urllib.parse import quote_plus
from urllib.parse import quote, quote_plus

from starlette.background import BackgroundTask
from starlette.concurrency import iterate_in_threadpool
Expand Down Expand Up @@ -229,7 +229,13 @@ def __init__(
self.background = background
self.init_headers(headers)
if self.filename is not None:
content_disposition = 'attachment; filename="{}"'.format(self.filename)
content_disposition_filename = quote(self.filename)
if content_disposition_filename != self.filename:
content_disposition = "attachment; filename*=utf-8''{}".format(
content_disposition_filename
)
else:
content_disposition = 'attachment; filename="{}"'.format(self.filename)
self.headers.setdefault("content-disposition", content_disposition)
self.stat_result = stat_result
if stat_result is not None:
Expand Down
15 changes: 15 additions & 0 deletions tests/test_responses.py
Original file line number Diff line number Diff line change
Expand Up @@ -202,6 +202,21 @@ def test_file_response_with_missing_file_raises_error(tmpdir):
assert "does not exist" in str(exc_info.value)


def test_file_response_with_chinese_filename(tmpdir):
content = b"file content"
filename = "你好.txt" # probably "Hello.txt" in Chinese
path = os.path.join(tmpdir, filename)
with open(path, "wb") as f:
f.write(content)
app = FileResponse(path=path, filename=filename)
client = TestClient(app)
response = client.get("/")
expected_disposition = "attachment; filename*=utf-8''%E4%BD%A0%E5%A5%BD.txt"
assert response.status_code == status.HTTP_200_OK
assert response.content == content
assert response.headers["content-disposition"] == expected_disposition


def test_set_cookie():
async def app(scope, receive, send):
response = Response("Hello, world!", media_type="text/plain")
Expand Down