加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

使用Django的测试客户端,使用内存文件发出请求

发布时间:2020-12-20 11:24:09 所属栏目:Python 来源:网络整理
导读:我正在为Django视图编写测试,我想发布一个文件.这是一个相当简单的测试,我不想用不同的文本文件丢弃我的tests /目录,所以我想使用内存文件并动态创建内容: from StringIO import StringIOfile = StringIO('content')client.post("/",data={'file': file})
我正在为Django视图编写测试,我想发布一个文件.这是一个相当简单的测试,我不想用不同的文本文件丢弃我的tests /目录,所以我想使用内存文件并动态创建内容:

from StringIO import StringIO
file = StringIO('content')
client.post("/",data={'file': file})

不幸的是,这不起作用:

Traceback (most recent call last):
  File "/Users/brad/project/tests/files.py",line 57,in test_set_and_save
    'mgmt-current_step': 'Attachments',File "/Users/brad/django/test/client.py",line 423,in post
    response = super(Client,self).post(path,data=data,content_type=content_type,**extra)
  File "/Users/brad/django/test/client.py",line 245,in post
    post_data = self._encode_data(data,content_type)
  File "/Users/brad/django/test/client.py",line 211,in _encode_data
    return encode_multipart(BOUNDARY,data)
  File "/Users/brad/django/test/client.py",line 117,in encode_multipart
    lines.extend(encode_file(boundary,key,value))
  File "/Users/brad/django/test/client.py",line 145,in encode_file
    content_type = mimetypes.guess_type(file.name)[0]
AttributeError: StringIO instance has no attribute 'name'

解决方法

Django附带了一组Python内置文件对象的包装器.在这种情况下,django.core.files.base.ContentFile是合适的:

from django.core.files.base import ContentFile
file = ContentFile(b'content',name='plain.txt')
client.post('/',data={'file': file})

ContentFile期望使用字节,因此不要给它unicode数据.

另一个技巧(如果你不关心文件的内容)是发送当前文件:

client.post('/',data={'file': open(__file__,'rb'))

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读