Is there a way to validate file size using python formencode?
-
30-04-2021 - |
Question
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.
Solution 3
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),
]
OTHER TIPS
You can use len() (in the validator) on the file object itself to check the file size, since its counting the bytes.
size = len(fileObj)
Sure there is - although I did that with turbogears, it should work with pyramid as well:
class MyFileValidator(FancyValidator):
def _to_python(self, value, state):
max_size = 10*1024*1024
payload = value.file.read(max_size+1)
# rewind so that the application can access the content
value.file.seek(0)
if len(payload) == max_size:
raise Invalid(u"The file is too big (>10MB)", value, state)
return value
class MySchema(Schema):
my_file = MyFileValidator(not_empty=True)
Note that read() ing the whole data should not be necessary (see other answer) - I did that for further content validation.