X-Git-Url: http://git.veekun.com/zzz-floof.git/blobdiff_plain/f4a6882d2cdb1baeb2c4662b1c305b99d7596cae..5837da26db915faca89925c39fa83202bfb84e32:/floof/lib/file_storage.py diff --git a/floof/lib/file_storage.py b/floof/lib/file_storage.py new file mode 100644 index 0000000..5595e88 --- /dev/null +++ b/floof/lib/file_storage.py @@ -0,0 +1,58 @@ +# This sucks. Make it not suck. +import os, shutil, tempfile, hashlib + +chunk_size = 1024*1024 # TODO: is this a good chunk size? + +""" +Notes: +# Here's one way to move stuff... +shutil.copyfileobj(temp.file, dest_file) + +# we should probably store the basename of the original filename in the database somewhere +temp_base = os.path.basename(temp.filename) + +# You can get a mime type like so: +from mimetypes import guess_type +guess_type(temp.filename)[0] +""" + + +def save_file(dest_root, temp): + # we don't know where we're going to save this stuff yet, + # so I guess we'll write it to another tempfile. One we know the path of. + # I'm assuming the tempfile we get from pylons is set to delete itself + # when it closes, and has no visible path. Maybe I'm wrong? + intermediate_file_descriptor, intermediate_path = tempfile.mkstemp() + + # that function gives me an integer file descriptor for some reason. + intermediate_file = os.fdopen(intermediate_file_descriptor, "wb") + + sha1 = hashlib.sha1() + while 1: + data = temp.file.read(chunk_size) + if not data: + break + sha1.update(data) + intermediate_file.write(data) + + temp.file.close() + intermediate_file.close() + hash = sha1.hexdigest() + + # git convention: first two characters are the directory + dest_dir = os.path.join( dest_root, hash[:2] ) + dest_path = os.path.join( dest_dir, hash[2:] ) + + makedirs(dest_dir) + os.rename(intermediate_path, dest_path) + + return hash + + + +def makedirs(dir): + try: + os.makedirs(dir) + except OSError: + pass + \ No newline at end of file