Commits

William Wu committed 3ebcb59

Initial import

Comments (0)

Files changed (7)

+Copyright (c) 2014 by William Wu.
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without modification,
+are permitted provided that the following conditions are met:
+
+    * Redistributions of source code must retain the above copyright
+      notice, this list of conditions and the following disclaimer.
+
+    * Redistributions in binary form must reproduce the above copyright notice,
+      this list of conditions and the following disclaimer in the documentation
+      and/or other materials provided with the distribution.
+
+    * The names of the contributors may not be used to endorse or promote
+      products derived from this software without specific prior written
+      permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
+ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+The API of this extension is inspired by
+
+`Flask-WTF <https://flask-wtf.readthedocs.org/en/latest/>`_ , but using different approches.
+
+This extension tries to provide consistent APIs, users do not need to be confued with
+
+different name spaces.
+
+This package provides extra file handling which meet request model of pyramid. Future version
+
+will provide csrf integration.

pyramid_wtf/__init__.py

+from . import validators
+from .fields import *
+from wtforms import widgets
+from wtforms.form import Form
+from wtforms.validators import ValidationError
+
+__version__ = '0.0.1'

pyramid_wtf/fields.py

+from . import widgets
+from wtforms.fields import *
+
+_FileField = FileField
+
+class FileField(_FileField):
+    '''
+    自訂配合 pyramid 使用的 FileField 類別,可接受一或多個檔案上傳
+    '''
+
+    def process_formdata(self, valuelist):
+        '檢查應該只有一個檔案'
+        if len(valuelist) != 1:
+            raise ValueError(self.gettext('Only one file is accepted.'))
+        self.data = valuelist[0]
+
+class MultiFilesField(_FileField):
+    '''
+    自訂配合 pyramid 使用的 FileField 類別,可接受多個檔案上傳
+    '''
+    widget = widgets.MultiFilesInput()
+
+    def process_formdata(self, valuelist):
+        self.data = valuelist

pyramid_wtf/validators.py

+from wtforms.validators import *
+
+class FileRequired(InputRequired):
+    '''
+    檢查是否有選擇檔案上傳
+    '''
+
+    def _check_fieldstorage(self, data):
+        '''
+        檢查 datalist 每個元素都應該是 cgi.FieldStorage 的 instance (多檔) 或是本身就是 cgi.FieldStorage
+        '''
+        from cgi import FieldStorage
+        if isinstance(data, list) and len(data) > 0:
+            for each_data in data:
+                if not isinstance(each_data, FieldStorage):
+                    return False
+            return True
+        elif isinstance(data, FieldStorage):
+            return True
+        return False
+
+    def __call__(self, form, field):
+        from wtforms.validators import StopValidation
+        if not self._check_fieldstorage(field.data):
+            if self.message is None:
+                message = field.gettext('This field is required for file(s).')
+            else:
+                message = self.message
+
+            field.errors[:] = []
+            raise StopValidation(message)
+
+class FileAllowed:
+    '''
+    檢查是否上傳符合要求的檔案類型
+    '''
+
+    def __init__(self, allowed_types, message=None):
+        '''
+        :param allowed_types: A list/tuple of extension names, ex. ['jpg', 'png']
+        '''
+        self.allowed_types = allowed_types
+        self.message       = message
+
+    def _check_allowed_types(self, data):
+        from cgi import FieldStorage
+        pass_flag = True
+        if isinstance(data, list):
+            for each_data in data:
+                if each_data.filename.split('.')[-1] not in self.allowed_types:
+                    pass_flag = False
+                    break
+        elif isinstance(data, FieldStorage):
+            if data.filename.split('.')[-1] not in self.allowed_types:
+                pass_flag = False
+        else:
+            pass_flag = False
+        return pass_flag
+
+    def __call__(self, form, field):
+        from wtforms.validators import ValidationError
+        if not self._check_allowed_types(field.data):
+            raise ValidationError(self.message)

pyramid_wtf/widgets.py

+from wtforms.widgets import *
+
+class MultiFilesInput:
+    """
+    Renders multiple files input chooser field.
+    """
+
+    def __call__(self, field, **kwargs):
+        kwargs.setdefault('id', field.id)
+        kwargs.setdefault('multiple', 'multiple')
+        return HTMLString('<input %s>' % html_params(name=field.name, type='file', **kwargs))
+from distutils.core import setup
+
+setup(
+    name='pyramid_wtf',
+    version='0.0.1',
+    packages=['pyramid_wtf',],
+    description='pyramid_wtf provides bindings for the Pyramid web framework to the WTForms library.',
+    author='William Wu',
+    author_email='william@pylabs.net',
+    url='https://bitbucket.org/williamwu/pyramid_wtf',
+    license='BSD',
+    long_description=open('README.txt').read(),
+    install_requires = ['pyramid==1.5', 'wtforms==1.0.5'],
+    classifiers=[
+        'Development Status :: 3 - Alpha',
+        'Programming Language :: Python :: 2.7',
+        'Programming Language :: Python :: 3',
+    ]
+)