Support status code for file reponse (#1269)

Fixes #1268
This commit is contained in:
Cosmo Borsky 2018-07-20 16:39:10 -04:00 committed by Raphael Deem
parent 599834b0e1
commit 377c9890a3
2 changed files with 11 additions and 10 deletions

View File

@ -233,8 +233,8 @@ def html(body, status=200, headers=None):
content_type="text/html; charset=utf-8")
async def file(
location, mime_type=None, headers=None, filename=None, _range=None):
async def file(location, status=200, mime_type=None, headers=None,
filename=None, _range=None):
"""Return a response object with file data.
:param location: Location of file on system.
@ -260,15 +260,14 @@ async def file(
out_stream = await _file.read()
mime_type = mime_type or guess_type(filename)[0] or 'text/plain'
return HTTPResponse(status=200,
return HTTPResponse(status=status,
headers=headers,
content_type=mime_type,
body_bytes=out_stream)
async def file_stream(
location, chunk_size=4096, mime_type=None, headers=None,
filename=None, _range=None):
async def file_stream(location, status=200, chunk_size=4096, mime_type=None,
headers=None, filename=None, _range=None):
"""Return a streaming response object with file data.
:param location: Location of file on system.
@ -315,7 +314,7 @@ async def file_stream(
headers['Content-Range'] = 'bytes %s-%s/%s' % (
_range.start, _range.end, _range.total)
return StreamingHTTPResponse(streaming_fn=_streaming_fn,
status=200,
status=status,
headers=headers,
content_type=mime_type)

View File

@ -227,17 +227,19 @@ def get_file_content(static_file_directory, file_name):
@pytest.mark.parametrize('file_name', ['test.file', 'decode me.txt', 'python.png'])
def test_file_response(file_name, static_file_directory):
@pytest.mark.parametrize('status', [200, 401])
def test_file_response(file_name, static_file_directory, status):
app = Sanic('test_file_helper')
@app.route('/files/<filename>', methods=['GET'])
def file_route(request, filename):
file_path = os.path.join(static_file_directory, filename)
file_path = os.path.abspath(unquote(file_path))
return file(file_path, mime_type=guess_type(file_path)[0] or 'text/plain')
return file(file_path, status=status,
mime_type=guess_type(file_path)[0] or 'text/plain')
request, response = app.test_client.get('/files/{}'.format(file_name))
assert response.status == 200
assert response.status == status
assert response.body == get_file_content(static_file_directory, file_name)
assert 'Content-Disposition' not in response.headers