Advertisement
Guest User

File Pool Django

a guest
Feb 22nd, 2011
486
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.86 KB | None | 0 0
  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)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement