from StringIO import StringIOfile = 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 Contentfilefile = Contentfile(b'content',name='plain.txt')clIEnt.post('/',data={'file': file})
Contentfile期望使用字节,因此不要给它unicode数据.
另一个技巧(如果你不关心文件的内容)是发送当前文件:
clIEnt.post('/',data={'file': open(__file__,'rb'))总结
以上是内存溢出为你收集整理的使用Django的测试客户端,使用内存文件发出请求全部内容,希望文章能够帮你解决使用Django的测试客户端,使用内存文件发出请求所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)