django RequestFactory文件上传 [英] django RequestFactory file upload

查看:91
本文介绍了django RequestFactory文件上传的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用RequestFactory创建一个请求,并使用文件进行发布,但没有收到request.FILES。

I try to create a request, using RequestFactory and post with file, but I don't get 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和我的文件?

How can I get request.FILES with my file ?

推荐答案

如果先打开文件,然后将request.FILES分配给打开的文件对象,则可以访问文件。

If you open the file first and then assign request.FILES to the open file object you can access your file.

request = self.factory.post('/')
with open(file, 'r') as f:
    request.FILES['file'] = f
    request.FILES['file'].read()

现在您可以像往常一样访问request.FILES。请记住,当您离开打开块请求时,FILES将是一个关闭的文件对象。

Now you can access request.FILES like you normally would. Remember that when you leave the open block request.FILES will be a closed file object.

这篇关于django RequestFactory文件上传的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆