2015-10-16 68 views
3

有沒有人有Python 3中Django的SimpleUploadedFile工作示例?Django SimpleUploadedFile與Python 3

此代碼工作在Python 2,但不是在Python 3

我有如下的測試:

test.py

class AttachmentModelTests(TestCase): 

    def setUp(self): 
     self.model = mommy.make(LocationLevel) 

     base_dir = dirname(dirname(dirname(__file__))) 
     self.image = join(base_dir, "source/attachments/test_in/test-mountains.jpg") 

    def test_create(self): 
     _file = SimpleUploadedFile(self.image, "file_content", 
      content_type="image/jpeg") 
     attachment = Attachment.objects.create(
      model_id=self.model.id, 
      file=_file 
     ) 

     self.assertIsInstance(attachment, Attachment) 
     self.assertEqual(
      attachment.filename, 
      self.image.split('/')[-1] # test-mountains.jpg 
     ) 

以下是錯誤它的輸出:

Traceback (most recent call last): 
    File "/Users/alelevier/Documents/bsrs/bsrs-django/bigsky/generic/tests/test_models.py", line 97, in test_create 
    content_type="image/jpeg") 
    File "/Users/alelevier/.virtualenvs/bs/lib/python3.4/site-packages/django/core/files/uploadedfile.py", line 114, in __init__ 
    super(SimpleUploadedFile, self).__init__(BytesIO(content), None, name, 
TypeError: 'str' does not support the buffer interface 

回答

0

This SO answer help me s幹掉它吧。

最後,這是更新工作的測試代碼:

def test_create(self): 
    (abs_dir_path, filename) = os.path.split(self.image) 

    with open(self.image) as infile: 
     _file = SimpleUploadedFile(filename, infile.read()) 
     attachment = Attachment.objects.create(
      model_id=self.model.id, 
      file=_file 
     ) 

     self.assertIsInstance(attachment, Attachment) 
     self.assertEqual(
      attachment.filename, 
      self.image.split('/')[-1] # test-mountains.jpg 
     ) 
+0

感謝。我發現在打開圖像時必須包含''rb'',即'open(self.image,'rb')as infile:'。 –