I'd like to validate uploaded file's size in my Pyramid application using formencode. As far as I understand, I need to create a class inherited from formencode.validators.FormValidator)
and put it to chained_validators
. But I can't figure out a way to check the uploaded file's size in the validate_python
method. Is it even possible?
Thanks in advance, Ivan.
Another way to do it:
class CheckFileSize(formencode.validators.FormValidator):
__unpackargs__ = ('upload_field', 'max_file_size')
def validate_python(self, value_dict, state):
log.info('test')
if value_dict.get(self.upload_field) is None:
return value_dict
fileobj = getattr(value_dict.get(self.upload_field), 'file', None)
fileobj.seek(0, os.SEEK_END)
if int(fileobj.tell()) > int(self.max_file_size):
raise formencode.Invalid(
_('File too big'),
value_dict, state,
error_dict={self.upload_field:
formencode.Invalid(_('File too big'), value_dict, state)})
return value_dict
class CreateNewCaseForm(formencode.Schema):
...
chained_validators = [
CheckFileSize('file', max_upload_size),
]