Django唯一文件名方法

2024-05-16 18:35:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我在寻找Django在上传文件时用来生成唯一文件名的方法。在

例如,如果我在同一目录中上载两次名为test.csv的文件,第一个文件将保存为test.csv,第二个文件将保存为test_2.csv。我已经试图找到Django是如何管理的,但我只找到了django.utils.text.get_valid_filename这可能有用,但这不是我要找的。。。在

我已经看到了othertopics的随机命名解决方案,这不是我在这里寻找的:)我真的想了解Django是如何处理这个问题的。在


Tags: 文件csvdjango方法texttest目录get
3条回答

如果您看到类django.core.files.storage.Storage的实现,您将知道Django 1.6如何管理文件名。在

查看这个类的save方法。在这条线上

name = self.get_available_name(name)

是在耍花招。在

这是在保存文件之前获取新文件名的默认实现。如果您想编写自己的版本(比如应该重写该文件),那么考虑编写自己的custom storage system

我在你的帮助下仔细看了一下,发现了一些东西:)

所以基本上我要做的是:

from django.core.files.storage import FileSystemStorage

fss = FileSystemStorage()
filepath = fss.get_available_name(filepath)

谢谢大家:)

附言:如果你感兴趣,来自django.core.file.storage.FileSystemStorage._save的评论说:

There's a potential race condition between get_available_name and saving the file; it's possible that two threads might return the same name, at which point all sorts of fun happens. So we need to try to create the file, but if it already exists we have to go back to get_available_name() and try again.

实际上,你走的是对的。在

docs开始

Internally, Django uses a django.core.files.File instance any time it needs to represent a file.

而且

Behind the scenes, Django delegates decisions about how and where to store files to a file storage system

这意味着,当上传文件时,使用默认存储(FileSystemStorage),Django在场景后面将文件的命名(或可用名称)委托给存储,然后存储使用:^{}。在

因此,如果您想更改上载时文件的命名方式,您需要添加一个自定义文件存储,它基本上只覆盖get_available_name。关于此事的文件是here。在

相关问题 更多 >