Rename file if it exists.
rsreese at gmail.com
Fri Oct 16 23:08:51 CEST 2009
> This isn't working because the else: is dangling. And I think your logic is
> flawed (I might be wrong of course) because you rename the *existing* file
> instead of giving the new one a new data.
> Thus e.g. a link to the file (if it's a webserver) will suddenly deliver a
> different file. I doubt that's what you wanted. And you also can only upload
> one file per *day*. Which doesn't sound good to me. You should disambiguate
> further. And if it's ok to append a date, I suggest you do that always.
> So instead, the logic should be something like this:
> import datetime
> basename = ... # however you get to that
> basename = basename + "_" + datetime.datetime.now().strftime("%Y-%m-%d")
> count = 0
> filename = basename
> while os.path.isfile(filename):
> filename = basename + "." + count
> count += 1
Ahh that would be much easier to just date the file upon upload. My
initial concern was that renaming the file would alter the hash value,
obviously I didn't think this one through too well.
I adjusted the code and tried to incorporate your recommendation but
still no go. Anything else obviously wrong with the following snippet?
# Test if the file was uploaded
# strip leading path from file name to avoid directory traversal attacks
fn = os.path.basename(fileitem.filename)
# Include date in filename.
basename = fn
basename = basename + "_" + datetime.datetime.now().strftime("%Y-%m-%d")
count = 0
fn = basename
fn = basename + "." + count
count += 1
# Open file for writing
f = open('/var/www/dropbox/' + fn, 'wb', 10000)
h = hashlib.md5()
datalength = 0
# Read the file in chunks
for chunk in fbuffer(fileitem.file):
datalength += len(chunk)
hexdigest = h.hexdigest()
message = 'The file "' + fn + '" was uploaded successfully with a
MD5 hash value of ' + hexdigest + ', click <a href="#">here</a> to go
More information about the Python-list