【发布时间】:2021-05-19 14:54:15
【问题描述】:
我在挣扎。问题在于单元测试(“test.py”),我想出了如何使用 tempfile 和 PIL 上传图像,但这些临时图像永远不会被删除。我考虑创建一个临时目录,然后使用 os.remove 删除该 temp_dir,但图像上传到不同的媒体目录取决于模型,所以我真的不知道如何发布 temp_images然后删除它们。
这是我的 models.py
class Noticia(models.Model):
...
img = models.ImageField(upload_to="noticias", storage=OverwriteStorage(), default="noticias/tanque_arma3.jpg")
...
test.py
def temporary_image():
import tempfile
from PIL import Image
image = Image.new('RGB', (100, 100))
tmp_file = tempfile.NamedTemporaryFile(suffix='.jpg', prefix="test_img_")
image.save(tmp_file, 'jpeg')
tmp_file.seek(0)
return tmp_file
class NoticiaTest(APITestCase):
def setUp(self):
...
url = reverse('api:noticia-create')
data = {'usuario': usuario.pk, "titulo":"test", "subtitulo":"test", "descripcion":"test", "img": temporary_image()}
response = client.post(url, data,format="multipart")
...
所以,总而言之,问题是,¿我如何从不同目录中删除临时文件,考虑到这些文件必须严格上传到这些目录上?
【问题讨论】:
-
在发布数据完成后尝试调用close(),如本例docs.python.org/3/library/tempfile.html#tempfile.mktemp
-
嘿 Pavan,我试过但结果相同,临时文件只是不想被删除。
-
平台/操作系统是什么
-
我使用的是 Windows 10
-
什么时候想删除它们。如果您想在使用 Noticia 调用 modelobject.delete() 后删除。那么你可以像stackoverflow.com/a/33081018/7887883那样使用post_delete信号
标签: python django django-rest-framework temporary-files