How to use the formencode.Invalid function in FormEncode

To help you get started, we’ve selected a few FormEncode examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github SEL-Columbia / networkplanner / np / controllers / people.py View on Github external
def changeAccount(valueByName, action, templatePath, person=None):
    'Validate values and send confirmation email if values are okay'
    try:
        # Validate form
        form = PersonForm().to_python(valueByName, person)
    except formencode.Invalid, error:
        return dict(isOk=0, errorByID=error.unpack_errors())
    else:
        # Purge expired candidates
        purgeExpiredPersonCandidates()
        # Prepare candidate
        candidate = model.PersonCandidate(form['username'], model.hashString(form['password']), form['nickname'], form['email'], form['email_sms'])
        candidate.person_id = person.id if person else None
        candidate.ticket = store.makeRandomUniqueTicket(parameter.TICKET_LENGTH, Session.query(model.PersonCandidate))
        candidate.when_expired = datetime.datetime.utcnow() + datetime.timedelta(days=parameter.TICKET_LIFESPAN_IN_DAYS)
        Session.add(candidate) 
        Session.commit()
        # Prepare recipient
        toByValue = dict(nickname=form['nickname'], email=form['email'])
        # Prepare subject
        subject = '[%s] Confirm %s' % (parameter.SITE_NAME, action)
        # Prepare body
github mediadrop / mediadrop / mediadrop / forms / admin / media.py View on Github external
def _to_python(self, value, state=None):
        if not value.strip():
            return (None, None)

        try:
            width, height = value.split('x')
        except ValueError, e:
            raise Invalid(
                _('Value must be in the format wxh; e.g. 200x300'),
                value, state)
        errors = []
        try:
            width = int(width)
        except ValueError, e:
            errors.append(_('Width must be a valid integer'))
        try:
            height = int(height)
        except ValueError, e:
            errors.append(_('Height must be a valid integer'))
        if errors:
            raise Invalid(u'; '.join(errors), value, state)

        if (width, height) == (0, 0):
            return (None, None)
github the-virtual-brain / tvb-framework / tvb / interfaces / web / controllers / settings_controller.py View on Github external
def _convert_to_python(self, value, _):
        try:
            return str(value).encode('ascii')
        except UnicodeError:
            raise formencode.Invalid('Invalid ascii string %s' % value, '', None)
github NOAA-ORR-ERD / PyGnome / web / gnome / Pyramid / miniGNOME / hazpy / formencodelib.py View on Github external
def validate_python(self, value, state):
        for field in self.fields:
            val = value.get(field)
            if val:
                return
        for field in self.fields_with_zero_allowed:
            val = value.get(field)
            if val or val == 0:
                return
        errmsg = "You must fill in at least one search criterion."
        raise fe.Invalid({"form": errmsg}, value, state)
github mediadrop / mediadrop / mediacore / lib / mediafiles.py View on Github external
def base_ext_container_from_uri(uri):
    """Returns a 3-tuple of strings:

    - Base of the filename (without extension)
    - Normalized file extension (without preceding dot)
    - Best-guess container format.

    Raises a formencode.Invalid exception if a useful container isn't found.
    """
    name, file_ext = os.path.splitext(uri)
    ext = file_ext[1:].lower()
    container = guess_container_format(ext)
    if container is None:
        # TODO: This block should actually never be reached. Ensure that it is not, and remove it.
        error_msg = _('File extension "%s" is not supported.') % file_ext
        raise formencode.Invalid(error_msg, None, None)
    return name, ext, container
github Othernet-Project / ndb-utils / ndb_utils / properties.py View on Github external
def _validate_python(self, value, state):
        if value < self.min:
            raise formencode.Invalid(self.message('too_small', state),
                                     value, state)
        if value > self.max:
            raise formencode.Invalid(self.message('too_large', state),
                                     value, state)
github apache / allura / Allura / allura / webhooks.py View on Github external
def update_webhook(self, wh, url, secret=None):
        if not secret:
            secret = self.gen_secret()
        wh.hook_url = url
        wh.secret = secret
        try:
            session(wh).flush(wh)
        except DuplicateKeyError:
            session(wh).expunge(wh)
            msg = u'_the_form: "{}" webhook already exists for {} {}'.format(
                wh.type, self.app.config.options.mount_label, url)
            raise Invalid(msg, None, None)
github apache / allura / Allura / allura / lib / widgets / forms.py View on Github external
    @ew_core.core.validator
    def to_python(self, value, state):
        d = super(PasswordChangeBase, self).to_python(value, state)
        if d['pw'] != d['pw2']:
            raise formencode.Invalid('Passwords must match', value, state)
        return d
github mediadrop / mediadrop / mediacore / lib / mediafiles.py View on Github external
from mediacore.lib.embedtypes import parse_embed_url
from mediacore.lib.thumbnails import create_default_thumbs_for, create_thumbs_for, has_thumbs, has_default_thumbs, thumb_path
from mediacore.model import Author, Media, MediaFile, MultiSetting, get_available_slug
from mediacore.model.meta import DBSession
from mediacore.plugin import events

import logging
log = logging.getLogger(__name__)

__all__ = [
    'add_new_media_file',
    'save_media_obj',
    'FTPUploadException',
]

class FTPUploadException(formencode.Invalid):
    pass

class UnknownRTMPServer(formencode.Invalid):
    pass

def parse_rtmp_url(url):
    """Attempt to parse an RTMP url.

    Returns None if the URL is not in the RTMP scheme.
    Returns (stream_url, file_name) tuple if a server is found.
    Raises UnknownRTMPServer exception if a server is not found.
    """
    if url.startswith('rtmp://'):
        # If this is an RTMP URL, check it against all known RTMP servers
        known_rtmp_servers = MultiSetting.query\
            .filter(MultiSetting.key==u'rtmp_server')\