1 # This sucks. Make it not suck.
2 import os
, shutil
, tempfile
, hashlib
4 chunk_size
= 1024*1024 # TODO: is this a good chunk size?
6 from pylons
import config
10 # Here's one way to move stuff...
11 shutil.copyfileobj(temp.file, dest_file)
13 # we should probably store the basename of the original filename in the database somewhere
14 temp_base = os.path.basename(temp.filename)
16 # You can get a mime type like so:
17 from mimetypes import guess_type
18 guess_type(temp.filename)[0]
21 def get_path(space
, hash):
22 return "/" + os
.path
.join( space
, hash[:2], hash[2:] )
25 def save_file(space
, temp
):
27 dest_root
= os
.path
.join( config
['app_conf']['static_root'], space
)
29 # we don't know where we're going to save this stuff yet,
30 # so I guess we'll write it to another tempfile. One we know the path of.
31 # I'm assuming the tempfile we get from pylons is set to delete itself
32 # when it closes, and has no visible path. Maybe I'm wrong?
33 intermediate_file_descriptor
, intermediate_path
= tempfile
.mkstemp()
35 # that function gives me an integer file descriptor for some reason.
36 intermediate_file
= os
.fdopen(intermediate_file_descriptor
, "wb")
40 data
= temp
.file.read(chunk_size
)
44 intermediate_file
.write(data
)
47 intermediate_file
.close()
48 hash = sha1
.hexdigest()
50 # git convention: first two characters are the directory
51 dest_dir
= os
.path
.join( dest_root
, hash[:2] )
52 dest_path
= os
.path
.join( dest_dir
, hash[2:] )
55 shutil
.move(intermediate_path
, dest_path
)