我尝试创建一个请求,使用RequestFactory和post with file,但我无法获得request.FILES。
from django.test.client import RequestFactory
from django.core.files import temp as tempfile
tdir = tempfile.gettempdir()
file = tempfile.NamedTemporaryFile(suffix=".file", dir=tdir)
file.write(b'a' * (2 ** 24))
file.seek(0)
post_data = {'file': file}
request = self.factory.post('/', post_data)
print request.FILES # get an empty request.FILES : <MultiValueDict: {}>如何使用我的文件获取request.FILES?
发布于 2015-10-16 04:02:57
如果首先打开文件,然后将request.FILES分配给打开的文件对象,则可以访问文件。
request = self.factory.post('/')
with open(file, 'r') as f:
request.FILES['file'] = f
request.FILES['file'].read()现在您可以像往常一样访问request.FILES了。请记住,当您离开打开的块时,request.FILES将是一个关闭的文件对象。
发布于 2017-12-21 04:09:24
我对@爱因斯坦的答案做了一些调整,以使其适用于将上传的文件保存在S3中的测试:
request = request_factory.post('/')
with open('my_absolute_file_path', 'rb') as f:
request.FILES['my_file_upload_form_field'] = f
request.FILES['my_file_upload_form_field'].read()
f.seek(0)
...'rb'身份打开文件的情况下,我在没有f.seek(0)的情况下使用文件数据发布于 2016-08-18 16:21:08
在更新FILES之前,您需要提供适当的内容类型、适当的文件对象。
from django.core.files.uploadedfile import File
# Let django know we are uploading files by stating content type
content_type = "multipart/form-data; boundary=------------------------1493314174182091246926147632"
request = self.factory.post('/', content_type=content_type)
# Create file object that contain both `size` and `name` attributes
my_file = File(open("/path/to/file", "rb"))
# Update FILES dictionary to include our new file
request.FILES.update({"field_name": my_file})boundary=------------------------1493314174182091246926147632是multipart表单类型的一部分。我从我的from浏览器完成的POST请求中复制了它。
https://stackoverflow.com/questions/14540446
复制相似问题