Fixed #27184 -- Allowed uploading TemporaryFile with the test client.

Thanks Federico Capoano for finishing the patch.
This commit is contained in:
Tom Scrace 2016-09-11 10:23:35 +01:00 committed by Tim Graham
parent f94ce0d21d
commit 5549e89b84
4 changed files with 19 additions and 1 deletions

View File

@ -226,7 +226,12 @@ def encode_multipart(boundary, data):
def encode_file(boundary, key, file):
def to_bytes(s):
return force_bytes(s, settings.DEFAULT_CHARSET)
filename = os.path.basename(file.name) if hasattr(file, 'name') else ''
# file.name might not be a string. For example, it's an int for
# tempfile.TemporaryFile().
file_has_string_name = hasattr(file, 'name') and isinstance(file.name, six.string_types)
filename = os.path.basename(file.name) if file_has_string_name else ''
if hasattr(file, 'content_type'):
content_type = file.content_type
elif filename:

View File

@ -22,6 +22,8 @@ rather than the HTML rendered to the end-user.
"""
from __future__ import unicode_literals
import tempfile
from django.contrib.auth.models import User
from django.core import mail
from django.http import HttpResponse
@ -714,6 +716,11 @@ class ClientTest(TestCase):
with self.assertRaisesMessage(Exception, 'exception message'):
self.client.get('/nesting_exception_view/')
def test_uploading_temp_file(self):
test_file = tempfile.TemporaryFile()
response = self.client.post('/upload_view/', data={'temp_file': test_file})
self.assertEqual(response.content, b'temp_file')
@override_settings(
MIDDLEWARE=['django.middleware.csrf.CsrfViewMiddleware'],

View File

@ -5,6 +5,7 @@ from django.views.generic import RedirectView
from . import views
urlpatterns = [
url(r'^upload_view/$', views.upload_view, name='upload_view'),
url(r'^get_view/$', views.get_view, name='get_view'),
url(r'^post_view/$', views.post_view),
url(r'^trace_view/$', views.trace_view),

View File

@ -324,3 +324,8 @@ def nesting_exception_view(request):
def django_project_redirect(request):
return HttpResponseRedirect('https://www.djangoproject.com/')
def upload_view(request):
"""Prints keys of request.FILES to the response."""
return HttpResponse(', '.join(request.FILES.keys()))