コード例 #1
0
ファイル: forms.py プロジェクト: dotajin/haoku-open
class Form(with_metaclass(FormMeta, WTForm)):
	class Meta(object):
		locales = ('zh_CN', 'zh')

	def is_submitted(self):
		return request and request.method in ('PUT', 'POST')

	def validate_on_submit(self):
		return self.is_submitted() and self.validate()
コード例 #2
0
 class F(with_metaclass(FMeta, Form)):
     pass
コード例 #3
0
ファイル: forms.py プロジェクト: txfyteen/chiki
class Form(with_metaclass(FormMeta, _Form), FormMixin):

    TIME_FORMAT = '%Y%m%d%H%M%S'
    TIME_LIMIT = timedelta(minutes=30)
    csrf_token = CSRFTokenField()

    def __init__(self, formdata=_Auto, obj=None, prefix='', **kwargs):
        if formdata is _Auto:
            if self.is_submitted():
                formdata = request.form
                if request.files:
                    formdata = formdata.copy()
                    formdata.update(request.files)
                elif request.json:
                    formdata = werkzeug.datastructures.MultiDict(request.json)
            else:
                formdata = None
        super(Form, self).__init__(formdata, obj, prefix, **kwargs)
        self.csrf_token.current_token = self.generate_csrf_token()

    def generate_csrf_token(self):
        secret_key = current_app.config.get('SECRET_KEY')
        if secret_key is None:
            raise Exception('must set SECRET_KEY in config for it to work')
        time_limit = current_app.config.get('SECRET_TIME_LIMIT',
                                            self.TIME_LIMIT)
        if 'csrf' not in session:
            session['csrf'] = sha1(os.urandom(64)).hexdigest()

        self.csrf_token.csrf_key = session['csrf']
        if time_limit:
            expires = (datetime.now() + time_limit).strftime(self.TIME_FORMAT)
            csrf_build = '%s%s' % (session['csrf'], expires)
        else:
            expires = ''
            csrf_build = session['csrf']

        hmac_csrf = hmac.new(secret_key,
                             csrf_build.encode('utf8'),
                             digestmod=sha1)
        return '%s##%s' % (expires, hmac_csrf.hexdigest())

    def validate_csrf_token(self, field):
        if not field.data or '##' not in field.data:
            raise ValidationError('CSRF token missing')

        secret_key = current_app.config.get('SECRET_KEY')

        expires, hmac_csrf = field.data.split('##')
        check_val = (field.csrf_key + expires).encode('utf8')
        hmac_compare = hmac.new(secret_key, check_val, digestmod=sha1)
        if hmac_compare.hexdigest() != hmac_csrf:
            raise ValidationError('CSRF failed')

        time_limit = current_app.config.get('SECRET_TIME_LIMIT',
                                            self.TIME_LIMIT)
        if time_limit:
            now_formatted = datetime.now().strftime(self.TIME_FORMAT)
            if now_formatted > expires:
                raise ValidationError('CSRF token expired')

    @property
    def data(self):
        d = super(Form, self).data
        d.pop('csrf_token')
        return d

    def populate_obj(self, obj):
        for name, field in self._fields.iteritems():
            if field.type != 'Label':
                field.populate_obj(obj, name)
コード例 #4
0
ファイル: forms.py プロジェクト: txfyteen/chiki
class BaseForm(with_metaclass(FormMeta, _Form), FormMixin):
    pass
コード例 #5
0
ファイル: form.py プロジェクト: codebynumbers/wtforms
class Form(with_metaclass(FormMeta, BaseForm)):
    """
    Declarative Form base class. Extends BaseForm's core behaviour allowing
    fields to be defined on Form subclasses as class attributes.

    In addition, form and instance input data are taken at construction time
    and passed to `process()`.
    """
    Meta = DefaultMeta

    def __init__(self,
                 formdata=None,
                 obj=None,
                 prefix='',
                 data=None,
                 meta=None,
                 **kwargs):
        """
        :param formdata:
            Used to pass data coming from the enduser, usually `request.POST` or
            equivalent. formdata should be some sort of request-data wrapper which
            can get multiple parameters from the form input, and values are unicode
            strings, e.g. a Werkzeug/Django/WebOb MultiDict
        :param obj:
            If `formdata` is empty or not provided, this object is checked for
            attributes matching form field names, which will be used for field
            values.
        :param prefix:
            If provided, all fields will have their name prefixed with the
            value.
        :param data:
            Accept a dictionary of data. This is only used if `formdata` and
            `obj` are not present.
        :param meta:
            If provided, this is a dictionary of values to override attributes
            on this form's meta instance.
        :param `**kwargs`:
            If `formdata` is empty or not provided and `obj` does not contain
            an attribute named the same as a field, form will assign the value
            of a matching keyword argument to the field, if one exists.
        """
        meta_obj = self._wtforms_meta()
        if meta is not None and isinstance(meta, dict):
            meta_obj.update_values(meta)
        super(Form, self).__init__(self._unbound_fields,
                                   meta=meta_obj,
                                   prefix=prefix)

        for name, field in iteritems(self._fields):
            # Set all the fields to attributes so that they obscure the class
            # attributes with the same names.
            setattr(self, name, field)
        self.process(formdata, obj, data=data, **kwargs)

    def __setitem__(self, name, value):
        raise TypeError(
            'Fields may not be added to Form instances, only classes.')

    def __delitem__(self, name):
        del self._fields[name]
        setattr(self, name, None)

    def __delattr__(self, name):
        if name in self._fields:
            self.__delitem__(name)
        else:
            # This is done for idempotency, if we have a name which is a field,
            # we want to mask it by setting the value to None.
            unbound_field = getattr(self.__class__, name, None)
            if unbound_field is not None and hasattr(unbound_field,
                                                     '_formfield'):
                setattr(self, name, None)
            else:
                super(Form, self).__delattr__(name)

    def validate(self):
        """
        Validates the form by calling `validate` on each field, passing any
        extra `Form.validate_<fieldname>` validators to the field validator.
        """
        extra = {}
        for name in self._fields:
            inline = getattr(self.__class__, 'validate_%s' % name, None)
            if inline is not None:
                extra[name] = [inline]

        return super(Form, self).validate(extra)
コード例 #6
0
ファイル: form.py プロジェクト: aparup/JoinHour.com-1
class Form(with_metaclass(FormMeta, BaseForm)):
    """
    Declarative Form base class. Extends BaseForm's core behaviour allowing
    fields to be defined on Form subclasses as class attributes.

    In addition, form and instance input data are taken at construction time
    and passed to `process()`.
    """
    def __init__(self, formdata=None, obj=None, prefix='', **kwargs):
        """
        :param formdata:
            Used to pass data coming from the enduser, usually `request.POST` or
            equivalent.
        :param obj:
            If `formdata` is empty or not provided, this object is checked for
            attributes matching form field names, which will be used for field
            values.
        :param prefix:
            If provided, all fields will have their name prefixed with the
            value.
        :param `**kwargs`:
            If `formdata` is empty or not provided and `obj` does not contain
            an attribute named the same as a field, form will assign the value
            of a matching keyword argument to the field, if one exists.
        """
        super(Form, self).__init__(self._unbound_fields, prefix=prefix)

        for name, field in iteritems(self._fields):
            # Set all the fields to attributes so that they obscure the class
            # attributes with the same names.
            setattr(self, name, field)

        self.process(formdata, obj, **kwargs)

    def __iter__(self):
        """ Iterate form fields in their order of definition on the form. """
        for name, _ in self._unbound_fields:
            if name in self._fields:
                yield self._fields[name]

    def __setitem__(self, name, value):
        raise TypeError(
            'Fields may not be added to Form instances, only classes.')

    def __delitem__(self, name):
        del self._fields[name]
        setattr(self, name, None)

    def __delattr__(self, name):
        try:
            self.__delitem__(name)
        except KeyError:
            super(Form, self).__delattr__(name)

    def validate(self):
        """
        Validates the form by calling `validate` on each field, passing any
        extra `Form.validate_<fieldname>` validators to the field validator.
        """
        extra = {}
        for name in self._fields:
            inline = getattr(self.__class__, 'validate_%s' % name, None)
            if inline is not None:
                extra[name] = [inline]

        return super(Form, self).validate(extra)
コード例 #7
0
ファイル: forms.py プロジェクト: dotajin/haoku-open
class Form(with_metaclass(FormMeta, WTForm)):
	class Meta(object):
		locales = ('zh_CN', 'zh')
コード例 #8
0
class Form(with_metaclass(FormMeta, BaseForm)):

    _DATA_TYPES = {'boolean': BooleanField, 'password': PasswordField}

    _RULES_MAP = {
        'email': validators.Email,
        'required': validators.InputRequired,
        'len': validators.Length
    }

    def __init__(self, formdata=None):
        self.boot()
        self._setup_unbound_fields()
        super(Form, self).__init__(self._unbound_fields)
        self.process(MultiDict(formdata))

    def boot(self):
        pass

    def rules(self):
        return []

    def _setup_unbound_fields(self):
        for field_name, field_rules in self.rules().items():
            field_type, validators = self._parse_rules(field_name, field_rules)

            field = (field_name,
                     UnboundField(field_type, field_name, validators))
            self._unbound_fields.append(field)

    def _parse_rules(self, field_name, rules):
        field_type = None
        validators = []

        for rule in rules:
            rule_name = rule
            rule_params = {}
            if isinstance(rule, tuple):
                rule_name, rule_params = rule

            if rule_name in self._DATA_TYPES:
                # Parse data type
                if not field_type:
                    field_type = self._DATA_TYPES[rule_name]
                else:
                    raise RuleException(
                        'Multiple data types defined for field: "{}"'.format(
                            field_name))
            else:
                # Parse validator
                validator = self._RULES_MAP.get(rule_name, None)
                if not validator:
                    raise RuleException(
                        'Undefined rule: "{}"'.format(rule_name))

                if isinstance(validator, types.FunctionType):
                    validators.append(validator)
                else:
                    validators.append(validator(**rule_params))

        field_type = StringField if not field_type else field_type
        return (field_type, validators)

    def register(self, rule_name, rule_function):
        self._RULES_MAP[rule_name] = rule_function