Python Flask将图像上传到S3 - 随机文件名从无处覆盖

时间:2017-03-10 10:43:30

标签: python flask

好吧,我目前面临一个奇怪的问题,我的文件名(正确生成的文件被随机覆盖)。

我正在使用此代码上传到AWS3,此处代码检查存储桶中是否已存在具有此类名称的文件,如果存在,则会在文件末尾添加1,然后继续检查现有文件并增加数字,直到文件名是唯一的。

我在一个单独的python文件中测试了代码,它似乎工作正常,但在这里我的文件名被随机字符串b1.a

覆盖

我现在正在调试一段时间,我不知道。我记得前段时间有过类似的东西,其中一个缺少的图标引起了这个问题(可能有人知道发生了什么以及这些问题是如何联系的)。但是这次我无法弄清楚发生了什么。

k.key = bucketpath + filename_hauptbild
if k.key in bucket:
    new_filename_haupt_split = filename_hauptbild.split(".")
    while k.key in bucket:
        if new_filename_haupt_split[0][-1] not in "0123456789":
            new_filename_haupt = new_filename_haupt_split[0] + "1." + new_filename_haupt_split[1]
        else:
            new_filename_haupt = new_filename_haupt_split[0][:-1] + str(int(new_filename_haupt_split[0][-1]) + 1) + "." + new_filename_haupt_split[1]
        new_filename_haupt_split = new_filename_haupt
        k.key = bucketpath + new_filename_haupt
        print  "this", new_filename_haupt
    k.key = bucketpath + new_filename_haupt
    filename_hauptbild = new_filename_haupt
    k.set_contents_from_string(file_contents)
else:
    k.set_contents_from_string(file_contents)

print filename_hauptbild
setattr(model_to_change, model_column, filename_hauptbild)

请注意: 我使用2 x prints,输出显示3行。 第一个print "this", new_filename_haupt首先显示正确的文件名,但被b1.a覆盖:

控制台输出: enter image description here

1 个答案:

答案 0 :(得分:1)

更新文件名时,无法正确更新_split变量:

new_filename_haupt_split = new_filename_haupt

因此,在你调用new_filename_haupt_split[0]的下一个循环中,你只需要获取文件名的第一个字母 - b - 而不是文件名本身,当你调用new_filename_haupt_split[1]时,你得到第二个字母 - a - 而不是扩展名。因此名称为b1.a。将您的行更改为:

new_filename_haupt_split = new_filename_haupt.split(".")

我认为这应该有用。

编辑:你可以重新编写这个功能,让你的生活更轻松一点。以下是您可能需要的方法示例:

bucket = ['baubedarf.png', 'baubedarf1.png']

def get_filename(input_filename, all_files):
    if input_filename in all_files:
        filename, ext = input_filename.rsplit('.', 1)
        counter = 1
        while '{}{}.{}'.format(filename, counter, ext) in all_files:
            counter += 1
        return '{}{}.{}'.format(filename, counter, ext)
    else:
        return input_filename

print get_filename('baubedarf.png', bucket)