我正在挣扎。问题出在单元测试(“test.py”)上,我想出了如何使用tempfile和PIL上传图像,但这些临时图像永远不会被删除。我考虑创建一个临时目录,然后使用os.remove删除该 temp_dir,但图像上传到不同的媒体目录取决于模型,所以我真的不知道如何发布 temp_images 然后删除它们。
\n这是我的models.py
\nclass Noticia(models.Model):\n ...\n img = models.ImageField(upload_to="noticias", storage=OverwriteStorage(), default="noticias/tanque_arma3.jpg")\n ...\nRun Code Online (Sandbox Code Playgroud)\n测试.py
\ndef temporary_image():\n import tempfile\n from PIL import Image\n\n image = Image.new(\'RGB\', (100, 100))\n tmp_file = tempfile.NamedTemporaryFile(suffix=\'.jpg\', prefix="test_img_")\n image.save(tmp_file, \'jpeg\')\n tmp_file.seek(0)\n return tmp_file\n\nclass NoticiaTest(APITestCase):\n def setUp(self):\n ...\n url = reverse(\'api:noticia-create\')\n data = {\'usuario\': usuario.pk, "titulo":"test", "subtitulo":"test", "descripcion":"test", "img": temporary_image()}\n response = client.post(url, data,format="multipart")\n\n ...\nRun Code Online (Sandbox Code Playgroud)\n所以,总而言之,问题是,\xc2\xbf如何从不同的目录中删除临时文件,考虑到这些文件必须严格上传到这些目录上?
\n