def test_set_file_object(self): # Create with File object. with open(self.testfile) as this_file: # Set a name explicitly ("uploaded"). wrapped_with_name = File( this_file, 'uploaded', metadata=self.file_metadata) # Name set from underlying file. wrapped = File(this_file, metadata=self.file_metadata) mwf = self.model(wrapped_with_name, wrapped).save() mwf.refresh_from_db() self.assertEqual('uploaded', os.path.basename(mwf.upload.name)) self.assertEqual('testfile.txt', os.path.basename(mwf.secondary_upload.name)) self.assertIn(b'Hello from testfile!', mwf.upload.read()) if self.file_metadata is not None: self.assertEqual(self.file_metadata['contentType'], mwf.upload.metadata['contentType'])
def test_set_file_object(self): # Create with File object. with open(self.image_src, 'rb') as image_src: wrapped = File(image_src, metadata={'contentType': 'image/png'}) mwi = self.ModelWithImage(wrapped).save() mwi.refresh_from_db() self.assertEqual(self.image_src, mwi.image.name) self.assertTrue(DB.fs.files.find_one().get('length')) self.assertEqual('image/png', mwi.image.metadata.get('contentType'))
def _to_field_file(self, value, inst): if isinstance(value, FieldFile): # No need to convert anything. return value # Convert builtin 'file' and others to a File object. if (not isinstance(value, File) and hasattr(value, 'read') and hasattr(value, 'name')): value = File(value, value.name, getattr(value, 'metadata', None)) # Wrap File objects in a FieldFile. if isinstance(value, File): ff = self._wrapper_class(inst, self, value.file_id) ff.file = value ff._committed = False return ff # Value might be the name/id of some file. return self._wrapper_class(inst, self, value)
def test_lazy_storage_initialization(self): conn_alias = 'test-field-file-no-connection' class ModelWithFileNoConnection(MongoModel): upload = FileField() class Meta: connection_alias = conn_alias with open(self.testfile) as this_file: model = ModelWithFileNoConnection( File(this_file, 'new', metadata=self.file_metadata), ) # With no connection, an exception should be thrown. with self.assertRaisesRegex( ValidationError, "No such alias {!r}".format( conn_alias)): model.save() # Should succeed once connection is created. connect_to_test_DB(conn_alias) model.save()
def open(self, name, mode='rb'): return File(open(self._path(name), mode))