Python mkstemp 后缀

-2 投票
2 回答
2390 浏览
提问于 2025-04-17 19:29

我在一个Django项目中有一段代码,用来处理图片上传:

def upload_handler(source):
    fd, filepath = tempfile.mkstemp(prefix=source.name, dir=MEDIA_ROOT)
    with open(filepath, 'wb') as dest:
        shutil.copyfileobj(source, dest)
        return MEDIA_URL + basename(dest.name)

上传的部分工作得很好,但我发现mkstemp这个函数在保存我的图片时,会在文件扩展名后面加上6个随机字符(比如说,test.png变成了test.pngbFVeyh)。即使我在第二行代码中传递了后缀,它也会加上这个后缀,但同时还会加上那6个随机字符。还有一个奇怪的事情是,在上传的文件夹(在我的情况下是MEDIA_ROOT)里,会生成一个和图片同名的空文本文件(比如说,test.pngbFVeyh)。我查阅了关于mkstemp的文档,但没有找到其他的解决办法。

2 个回答

2
def upload_handler(source):
    # this is creating a temp file and returning an os handle and name
    fd, filepath = tempfile.mkstemp(prefix=source.name, dir=MEDIA_ROOT)
    # this next line just clears the file you just made (which is already empty)
    with open(filepath, 'wb') as dest: 
        # this is a strange way to get a fobj to copy :)
        shutil.copyfileobj(source, dest)
        return MEDIA_URL + basename(dest.name)

前缀和后缀就是用来做这个的,所以如果你不想你的文件名开头或结尾有临时字符,就需要同时使用前缀后缀。例如,

name = os.path.basename(source.name)
prefix, suffix = os.path.splitext(name)
_, filepath = tempfile.mkstemp(prefix=prefix, suffix=suffix, dir=MEDIA_ROOT)

不过,如果你使用 tempfile.NamedTemporaryFile 会更好,因为这样会返回一个类似文件的对象(所以你不需要从文件名创建 fobj,并且临时文件在完成后默认会被删除)。

fobj, _ = tempfile.NamedTemporaryFile(prefix=prefix, suffix=suffix, dir=MEDIA_ROOT)
shutil.copyfileobj(source, fobj)
-1

这个名字是随机生成的,因为这就是tempfile.mkstemp的目的。用这个名字创建的文件是因为tempfile.mkstemp的工作方式就是这样。这个文件会被打开,并且文件描述符会以fd的形式返回给你,但你似乎没有去关注它。看起来你对tempfile.mkstemp的用法不是很了解,可能需要使用其他的东西。

撰写回答