api_views: test if file exists before returning the StreamingHttpResponse

This commit is contained in:
Benjamin Dauvergne 2017-09-27 17:10:04 +02:00
parent 45f8b4bc9c
commit 2a1cec8205
2 changed files with 22 additions and 0 deletions

View File

@ -167,6 +167,7 @@ class PetalAPIView(APIView):
@logit
def get(self, request, partner_name, cut_uuid, petal_name):
logger = logging.getLogger(__name__)
if_none_match = request.META.get('HTTP_IF_NONE_MATCH')
if_none_match = if_none_match and map(str.strip, if_none_match.split(','))
@ -179,6 +180,13 @@ class PetalAPIView(APIView):
'ETag': petal.etag
}
)
# verify file exists before creating a StreamingHttpResponse
# as StreamingHttpResponse generate its content after the Django global try/catch
try:
petal.data.open()
except IOError as e:
logger.error('file not found "%s": %s', petal.data.path, e)
return HttpResponse('missing file', status=500)
response = StreamingHttpResponse(
petal.data.chunks(),
content_type=petal.content_type,

View File

@ -1,3 +1,4 @@
import os
import json
from xml.etree import ElementTree as etree
@ -390,3 +391,16 @@ def test_cut_uuid_idp_checking(mocked_post, settings, app, acl):
headers=headers, status=201)
assert CUT.objects.get(uuid=cut_uuid)
assert Petal.objects.get(name='profile', cut__uuid=cut_uuid, partner__name='southpark')
def test_storage_error(app, partner_southpark, cut_kevin_uuid, acl, caplog):
app.authorization = ('Basic', ('library', 'library'))
payload = json.loads(get_tests_file_content('books.json'))
url = '/api/southpark/%s/loans/' % cut_kevin_uuid
app.put_json(url, params=payload, headers={'If-None-Match': '*'}, status=201)
os.unlink(Petal.objects.get().data.path)
app.get(url, status=500)