Back to index

plone3  3.1.7
SupplValidators.py
Go to the documentation of this file.
00001 try:
00002     from Products.validation.interfaces.IValidator import IValidator
00003     from Acquisition import aq_base
00004 except ImportError:
00005     import sys, os
00006     sys.path.insert(0, os.path.join(os.path.dirname(__file__), os.pardir))
00007     from interfaces.IValidator import IValidator
00008     del sys, os
00009 
00010 _marker = []
00011 
00012 try:
00013     True
00014 except NameError:
00015     True=1
00016     False=0
00017 
00018 from types import FileType
00019 try:
00020     from ZPublisher.HTTPRequest import FileUpload
00021 except ImportError:
00022     FileUpload = FileType
00023 
00024 class MaxSizeValidator:
00025     """Tests if an upload, file or something supporting len() is smaller than a 
00026        given max size value
00027        
00028     If it's a upload or file like thing it is using seek(0, 2) which means go
00029     to the end of the file and tell() to get the size in bytes otherwise it is
00030     trying to use len()
00031     
00032     The maxsize can be acquired from the kwargs in a call, a 
00033     getMaxSizeFor(fieldname) on the instance, a maxsize attribute on the field
00034     or a given maxsize at validator initialization.
00035     """
00036     __implements__ = IValidator
00037 
00038     def __init__(self, name, title='', description='', maxsize=0):
00039         self.name = name
00040         self.title = title or name
00041         self.description = description
00042         self.maxsize= maxsize
00043 
00044     def __call__(self, value, *args, **kwargs):
00045         instance = kwargs.get('instance', None)
00046         field    = kwargs.get('field', None)
00047 
00048         # get max size
00049         if kwargs.has_key('maxsize'):
00050             maxsize = kwargs.get('maxsize')
00051         elif hasattr(aq_base(instance), 'getMaxSizeFor'):
00052             maxsize = instance.getMaxSizeFor(field.getName())
00053         elif hasattr(field, 'maxsize'):
00054             maxsize = field.maxsize
00055         else:
00056             # set to given default value (default defaults to 0)
00057             maxsize = self.maxsize
00058         
00059         if not maxsize:
00060             return True
00061         
00062         # calculate size
00063         elif isinstance(value, FileUpload) or type(value) is FileType \
00064           or hasattr(aq_base(value), 'tell'):
00065             value.seek(0, 2) # eof
00066             size = value.tell()
00067             value.seek(0)
00068         else:
00069             try:
00070                 size = len(value)
00071             except TypeError:
00072                 size = 0
00073         size = float(size)
00074         sizeMB = (size / (1024 * 1024))
00075 
00076         if sizeMB > maxsize:
00077             return ("Validation failed(%(name)s: Uploaded data is too large: %(size).3fMB (max %(max)fMB)" %
00078                      { 'name' : self.name, 'size' : sizeMB, 'max' : maxsize })
00079         else:
00080             return True
00081 
00082 
00083 try:
00084     from DateTime import DateTime
00085 except ImportError:
00086     # XXX use python datetime?
00087     DateTime = lambda date: None
00088 
00089 class DateValidator:
00090 
00091     __implements__ = IValidator
00092 
00093     def __init__(self, name, title='', description=''):
00094         self.name = name
00095         self.title = title or name
00096         self.description = description
00097 
00098     def __call__(self, value, *args, **kwargs):
00099         if not value:
00100             return ("Validation failed(%s): value is "
00101                     "empty (%s)." % (self.name, repr(value)))
00102         if not isinstance(value, DateTime):
00103             try:
00104                 value = DateTime(value)
00105             except:
00106                 return ("Validation failed(%s): could not "
00107                         "convert %s to a date.""" % (self.name, value))
00108         return True
00109 
00110 
00111 validatorList = [
00112     MaxSizeValidator('isMaxSize', title='', description=''),
00113     DateValidator('isValidDate', title='', description=''),
00114     ]
00115 
00116 __all__ = ('validatorList', )
00117