Pastebin launched a little side project called VERYVIRAL.com, check it out ;-) Want more features on Pastebin? Sign Up, it's FREE!
Guest

File Pool Django

By: a guest on Feb 22nd, 2011  |  syntax: Python  |  size: 0.86 KB  |  views: 369  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. import hashlib
  2. from django.core.files.storage import FileSystemStorage
  3. import os
  4.  
  5. def md5sum(file):
  6.     """Calculate the md5 checksum of a file-like object without reading its
  7.    whole content in memory.
  8.  
  9.    >>> from StringIO import StringIO
  10.    >>> md5sum(StringIO('file content to hash'))
  11.    '784406af91dd5a54fbb9c84c2236595a'
  12.    """
  13.     m = hashlib.md5()
  14.     while 1:
  15.         d = file.read(8096)
  16.         if not d:
  17.             break
  18.         m.update(d)
  19.     return m.hexdigest()
  20.  
  21. class PoolStorage(FileSystemStorage):
  22.     """
  23.    Saves file in file pool ;)
  24.    """                                                              
  25.     def _save(self, name, content):
  26.         oname = name.split('/')
  27.         key = md5sum(content)
  28.         name = os.path.join(oname[0], key[0:2], oname[1])
  29.         return super(PoolStorage, self)._save(name, content)
clone this paste RAW Paste Data