class ContactSchema(c.MappingSchema): name = c.SchemaNode(c.Str(), title=_('Name'), widget=d.widget.TextInputWidget(size=60, maxlength=160)) email = c.SchemaNode(c.Str(), title=_('Email'), validator=c.Email(), widget=d.widget.TextInputWidget(size=50, maxlength=160, type='email')) subject = c.SchemaNode(c.Str(), title=_('Subject'), widget=d.widget.TextInputWidget( size=60, maxlength=160)) message = c.SchemaNode(c.Str(), title=_('Message'), widget=d.widget.TextAreaWidget(cols=60, rows=12)) if len_name: name.widget.maxlength = len_name.get('max') name.validator = c.Length(**len_name) if len_subject: subject.validator = c.Length(**len_subject) if len_message: message.validator = c.Length(**len_message)
def get_schema_node(self): kw = self._get_schema_node_args(defaul=False) date_default = self.field.get_option('defaul') if date_default != '': kw['default'] = date_default month_selector = self.field.get_option('month_selector') == 'true' year_selector = self.field.get_option('year_selector') == 'true' show_week = self.field.get_option('show_week') == 'true' calendar_config = dict(changeMonth=month_selector, changeYear=year_selector, showWeek=show_week, dateFormat=df.formats[int(self.field.get_option \ ('input_date_format'))]['js']) def date_validation(node, val): try: date = datetime.strptime(val, df.formats[int(self.field.get_option \ ('input_date_format'))]['py']) except ValueError: raise c.Invalid(node, _("Invalid date format")) kw['date_format_js'] = df.formats[int(self.field.get_option \ ('input_date_format'))]['js'] kw['date_format_py'] = df.formats[int(self.field.get_option \ ('input_date_format'))]['py'] kw['calendar_config'] = json.dumps(calendar_config) kw['validator'] = date_validation if self.field.required: sn = c.SchemaNode(c.Str(), **kw) else: sn = c.SchemaNode(c.Str(), missing=c.null, **kw) return sn
class AirlineSchema(colander.MappingSchema): name = colander.SchemaNode(colander.Str(), description='Airline name') two_digit_code = colander.SchemaNode(colander.Str(), description='2_digit_code') three_digit_code = colander.SchemaNode(colander.Str(), description='3_digit_code') country = colander.SchemaNode(colander.Str(), description='Airline country')
class ContactFormSchema(c.MappingSchema): name = c.SchemaNode(c.Str(), title=_('Name'), validator=c.Length(**LEN_NAME)) email = c.SchemaNode(c.Str(), title=_('Email'), validator=c.Email()) subject = c.SchemaNode(c.Str(), title=_('Subject'), validator=c.Length(**LEN_SUBJECT)) message = c.SchemaNode(c.Str(), title=_('Message'), widget=TextAreaWidget(cols=40, rows=12), validator=c.Length(**LEN_MESSAGE))
class AuthorizationCodeSchema(c.Schema): """AccessToken request schema. Authorization code is used to request an access token """ code = c.SchemaNode(c.Str(), required=True) client_id = c.SchemaNode(c.Int(), required=True)
def get_schema_node(self): kw = self._get_schema_node_args(defaul=True) if not self.field.required: kw['missing'] = kw['defaul'] kw['validator'] = c.Email(msg='Please enter a valid email address' ' such as "*****@*****.**".') return c.SchemaNode(c.Str(), **kw)
def main(options): root_logger = logging.getLogger() root_logger.addHandler(logging.StreamHandler(sys.stdout)) root_logger.setLevel(getattr(logging, options.log_level.upper())) log.debug(options) nbhd = M.Neighborhood.query.get(name=options.neighborhood) if not nbhd: return 'Invalid neighborhood "%s".' % options.neighborhood data = json.load(open(options.file, 'r')) projectSchema = make_newproject_schema(nbhd, options.update) # allow 'icon' as a local filesystem path via this script only projectSchema.add( colander.SchemaNode(colander.Str(), name='icon', missing=None)) projects = [] for datum in data: try: if options.update and not datum.get('shortname'): log.warning( 'Shortname not provided with --update; this will create new projects instead of updating' ) projects.append(deserialize_project(datum, projectSchema, nbhd)) except Exception: keep_going = options.validate_only log.error('Error on %s\n%s', datum['shortname'], datum, exc_info=keep_going) if not keep_going: raise log.debug(projects) if options.validate_only: return for p in projects: log.info('Creating%s project "%s".' % ('/updating' if options.update else '', p.shortname)) try: project = create_project_with_attrs( p, nbhd, update=options.update, ensure_tools=options.ensure_tools) except Exception as e: log.exception('%s' % (str(e))) project = False if not project: log.warning('Stopping due to error.') return 1 session(project).clear() log.warning('Done.') return 0
def create_category_schema(user): '''Returns a schema for creation of a category, imperatively built''' schema = c.SchemaNode(c.Mapping()) schema.add( c.SchemaNode(c.Str(), name="name", title=_('Name'), validator=c.All(c.Length(**LEN_NAME), validate_based_on_user(user)))) schema.add( c.SchemaNode(c.Str(), name="description", title=_('Description'), missing='', validator=c.Length(**LEN_DESCRIPTION))) return schema
class Project(col.MappingSchema): name = col.SchemaNode(ProjectNameType()) shortname = col.SchemaNode(ProjectShortnameType(), missing=None) summary = col.SchemaNode(col.Str(), missing='') description = col.SchemaNode(col.Str(), missing='') admin = col.SchemaNode(User()) private = col.SchemaNode(col.Bool(), missing=False) labels = Labels(missing=[]) external_homepage = col.SchemaNode(col.Str(), missing='') trove_root_databases = TroveDatabases(missing=None) trove_developmentstatuses = TroveStatuses(validator=col.Length(max=6), missing=None) trove_audiences = TroveAudiences(validator=col.Length(max=6), missing=None) trove_licenses = TroveLicenses(validator=col.Length(max=6), missing=None) trove_oses = TroveOSes(missing=None) trove_languages = TroveLanguages(validator=col.Length(max=6), missing=None) trove_topics = TroveTopics(validator=col.Length(max=3), missing=None) trove_natlanguages = TroveTranslations(missing=None) trove_environments = TroveUIs(missing=None)
class ForgotPasswordSchema(CSRFSchema): """Used on forgot password view.""" email = c.SchemaNode( c.Str(), title='Email', validator=c.All(c.Email(), validate_user_exists_with_email), widget=w.TextInputWidget(size=40, maxlength=260, type='email', template="textinput_placeholder"), description="The email address under which you have your account. Example: [email protected]")
class ForgotPasswordSchema(CSRFSchema): email = c.SchemaNode( c.Str(), title=_('Email'), validator=c.All(c.Email(), email_exists), # type='email' will render an HTML5 email field # if you use deform_bootstrap_extra: widget=w.TextInputWidget(size=40, maxlength=260, type='email'), description=_("The email address under which you have your account. " "Example: [email protected]"))
class LoginSchema(colander.Schema): login = colander.SchemaNode( colander.Str(), validator=colander.Length(min=5, max=100), ) password = colander.SchemaNode( colander.String(), validator=colander.Length(min=5, max=100), widget=deform.widget.PasswordWidget(size=20), description='Enter a password') captcha = colander.SchemaNode(colander.String(), title='Verify you are human', widget=deferred_recaptcha_widget)
class AirportSchema(colander.MappingSchema): name = colander.SchemaNode(colander.Str(), description='Airport name') city = colander.SchemaNode(colander.Str(), description='Aiport city') country = colander.SchemaNode(colander.Str(), description='Airport country') iata_3 = colander.SchemaNode(colander.Str(), description='IATA_3') latitute = colander.SchemaNode(colander.Str(), description='Latitude') longitude = colander.SchemaNode(colander.Str(), description='Longitude')
class FormSchema(c.MappingSchema): name = c.SchemaNode(c.Str(), title=_('Form title'), description=_("name your form"), missing='', validator=c.Length(min=0, max=length(Form.name))) description = c.SchemaNode(c.Str(), title=_('Description'), widget=d.widget.TextAreaWidget(rows=5), default='', missing='', description=_("description of this form")) use_rich = c.SchemaNode(c.Boolean(), title=_('form header in rich text'), default=False, missing=False, description=_('for the form name and description')) submit_label = c.SchemaNode( c.Str(), title=_('Text for "Submit" button'), default=_('Submit'), missing=_('Submit'), description=_("name of the button used to submit the form"))
def create_website_code_schema(): invitation_message = c.SchemaNode(c.Str(), name='invitation_message', missing='') invitation_popup_width = c.SchemaNode(c.Int(), name='invitation_popup_width') invitation_popup_height = c.SchemaNode(c.Int(), name='invitation_popup_height') embed_frame_height = c.SchemaNode(c.Int(), name='embed_frame_height') extra_fields = [ invitation_popup_width, invitation_popup_height, embed_frame_height, invitation_message ] return create_collector_schema(extra_fields)
def create_collector_schema(extra_fields=None): name = c.SchemaNode(c.Str(), name='name', validator=c.Length(max=get_length(Collector, 'name'))) on_completion = c.SchemaNode(c.Str(), name='on_completion', validator=c.OneOf( Collector.ON_COMPLETION_VALUES)) thanks_url = c.SchemaNode( c.Str(), name='thanks_url', missing='', validator=c.All(c.Length(max=get_length(Collector, 'thanks_url')), web_url)) thanks_message = c.SchemaNode(c.Str(), name='thanks_message', missing='') email_each_entry = c.SchemaNode(c.Boolean(), name='email_each_entry', missing=False) limit_by_date = c.SchemaNode(c.Boolean(), name='limit_by_date', missing=False) message_after_end = c.SchemaNode(c.Str(), name='message_after_end', missing='') message_before_start = c.SchemaNode(c.Str(), name='message_before_start', missing='') start_date = c.SchemaNode(c.Str(), name='start_date', missing='', validator=date_string) end_date = c.SchemaNode(c.Str(), name='end_date', missing='', validator=c.All(date_string, in_the_future)) args = [ name, on_completion, thanks_url, thanks_message, email_each_entry, limit_by_date, message_before_start, message_after_end, start_date, end_date ] if (extra_fields): args.extend(extra_fields) collector_schema = c.SchemaNode(c.Mapping(), *args, validator=valid_interval) return collector_schema
class LoginFormSchema(colander.MappingSchema): ''' login form schema define ''' email = colander.SchemaNode( colander.Str(), title='Email', validator=colander.All(colander.Email()), widget=deform.widget.TextInputWidget(size=40, maxlength=260, type='email', placeholder="*****@*****.**"), description="The email address under which you have your account.") password = colander.SchemaNode( colander.String(), validator=colander.Length(min=5, max=100), widget=deform.widget.PasswordWidget(), description='Enter a password')
def language_dropdown(settings, title=_('Locale'), name='locale', blank_option_at_top=True): '''If you use Deform, you can use this to get a SchemaNode that lets the user select a locale from the enabled ones. ''' import colander as c import deform as d def options(): if blank_option_at_top: yield ('', _('- Choose -')) for loc in settings[SETTING_NAME].values(): yield (loc.code, loc.display_name) values = sorted(options(), key=lambda t: _(t[1])) return c.SchemaNode(c.Str(), title=title, name=name, validator=locale_exists_validator(settings), widget=d.widget.SelectWidget(values=values))
def get_schema_node(self): f = self.field params = self._get_schema_node_args(defaul=False) precision = int(f.get_option('precision')) separator = f.get_option('separator') params['default'] = f.get_option('defaul') if separator == ',': params['default'] = params['default'].replace('.', ',') if not f.required: params['missing'] = '' if precision == 0: params['validator'] = get_validator('integer') else: params['validator'] = get_validator('decimal', separator=separator, precision=precision) params['prefix'] = f.get_option('prefix') params['suffix'] = f.get_option('suffix') return c.SchemaNode(c.Str(), **params)
class SiteProfileForm(colander.MappingSchema): name = colander.SchemaNode(colander.Str(), title="Municipality Name", widget=TextInputWidget(size=30)) box_volume = colander.SchemaNode( colander.Float(), title="Standard Box's Volume (m3)", validator=colander.Range(min=MIN_VOLUME, min_err="The length must be greater than 0")) wheelbarrow_volume = colander.SchemaNode( colander.Float(), title="Wheelbarrow's Volume (m3)", validator=colander.Range(min=MIN_VOLUME, min_err="The length must be greater than 0")) leachete_tank_length = colander.SchemaNode( colander.Float(), title="Leachete Tank's Length (m)", validator=colander.Range(min=MIN_VOLUME, min_err="The length must be greater than 0")) leachete_tank_width = colander.SchemaNode( colander.Float(), title="Leachete Tank's Width (m)", validator=colander.Range(min=MIN_VOLUME, min_err="The length must be greater than 0"))
class NewProjectSchema(col.MappingSchema): def schema_type(self, **kw): return col.Mapping(unknown='raise') name = col.SchemaNode(col.Str()) summary = col.SchemaNode(col.Str(), missing='') description = col.SchemaNode(col.Str(), missing='') admin = col.SchemaNode(User()) private = col.SchemaNode(col.Bool(), missing=False) labels = Labels(missing=[]) external_homepage = col.SchemaNode(col.Str(), missing='') video_url = col.SchemaNode(col.Str(), missing='') trove_root_databases = TroveDatabases(missing=None) trove_developmentstatuses = TroveStatuses(validator=col.Length(max=6), missing=None) trove_audiences = TroveAudiences(validator=col.Length(max=6), missing=None) trove_licenses = TroveLicenses(validator=col.Length(max=6), missing=None) trove_oses = TroveOSes(missing=None) trove_languages = TroveLanguages(validator=col.Length(max=6), missing=None) trove_topics = TroveTopics(validator=col.Length(max=3), missing=None) trove_natlanguages = TroveTranslations(missing=None) trove_environments = TroveUIs(missing=None) tool_data = col.SchemaNode(col.Mapping(unknown='preserve'), missing={}) icon_url = col.SchemaNode(col.Str(), missing=None, validator=col.url)
def get_schema_node(self): title = self.field.label list_type = self.field.get_option('list_type') new_option = self.field.get_option('new_option') == 'true' sort_choices = self.field.get_option('sort_choices') multiple_choice = self.field.get_option('multiple_choice') == 'true' valuesQuery = sas.query(ListOption) \ .filter(ListOption.field_id == self.field.id) \ .filter(ListOption.status != 'Rejected') \ .filter(ListOption.status != 'Awaiting moderation') if sort_choices == 'user_defined': valuesObjs = valuesQuery.order_by(ListOption.position).all() elif sort_choices == 'random': valuesObjs = valuesQuery.all() elif sort_choices == 'alpha_asc': valuesObjs = valuesQuery.order_by(ListOption.label).all() elif sort_choices == 'alpha_desc': valuesObjs = valuesQuery.order_by(ListOption.label.desc()).all() values_tup = [(v.id, v.label) for v in valuesObjs] if sort_choices == 'random': random.shuffle(values_tup) values = tuple(values_tup) opt_restrictions = self.field.get_option('opt_restrictions') min_num = self.field.get_option('min_num') max_num = self.field.get_option('max_num') def valid_require(node, value): if self.field.get_option('new_option') == 'true': if self.field.required: if list_type != 'radio': if not value['option'].difference(set([''])) \ and not value['other']: raise c.Invalid(node, _('Required.')) else: if not value['option'] and not value['other']: raise c.Invalid(node, _('Required.')) elif self.field.required: if list_type != 'radio': if not value['option'].difference(set([''])): raise c.Invalid(node, _('Required.')) elif not value['option']: raise c.Invalid(node, _('Required.')) def min_choices(node, value): try: int(min_num) except ValueError: return if self.field.get_option('new_option') == 'true': add = 1 if value['other'] != '' else 0 else: add = 0 lacking_options = int(min_num) - \ len(value['option'].difference(set(['']))) + add if lacking_options > 0: if lacking_options == 1: raise c.Invalid(node, _('Please select one more option.')) else: raise c.Invalid(node, _('Please select {0} more options.'). \ format(lacking_options)) def max_choices(node, value): try: imax_num = int(max_num) except ValueError: return if self.field.get_option('new_option') == 'true': add = 1 if value['other'] != '' else 0 else: add = 0 excess_number = \ len(value['option'].difference(set(['']))) + \ add - imax_num if imax_num != 0 and excess_number > 0: if excess_number == 1: raise c.Invalid(node, _('Please deselect one option.')) else: raise c.Invalid(node, _('Please deselect {0} options.'). \ format(excess_number)) schema_params = {} if list_type == 'select' or list_type == 'checkbox': if opt_restrictions and multiple_choice: schema_params['validator'] = c.All(valid_require, min_choices, max_choices) schema_params['min_num'] = min_num schema_params['max_num'] = max_num else: schema_params['validator'] = valid_require else: schema_params['validator'] = valid_require if not self.field.required: schema_params['missing'] = {} schema_params['default'] = {} schema_params['multiple_choice'] = multiple_choice # Create the Mapping for select field list_map_schema = c.SchemaNode(c.Mapping(), title=title, name='input-{0}'.format(self.field.id), description=self.field.description, widget=d.widget.MappingWidget(template='form_select_mapping', item_template='form_select_mapping_item', error_class='error'), rich=self.field.rich, use_rich=self.field.use_rich, parent_id=self.field.id, opt_restrictions=self.field.get_option('opt_restrictions'), multiple=self.field.get_option('multiple_choice'), list_type=list_type, **schema_params) options = sas.query(ListOption) \ .filter(ListOption.field_id == self.field.id) \ .filter(ListOption.opt_default == True) \ .all() options_id = [o.id for o in options] req_dict = {'missing': '', 'default': ''} if list_type == 'select': list_schema = c.SchemaNode(d.Set(allow_empty=True), title=title, name='option', widget=d.widget.SelectWidget( values=values, template='form_select'), defaults=options_id, req=self.field.required, has_other=new_option, description=self.field.description, multiple=self.field.get_option('multiple_choice'), size_options=self.field.get_option('size_options'), parent_id=self.field.id, **req_dict) elif list_type == 'radio': option = sas.query(ListOption) \ .filter(ListOption.field_id == self.field.id) \ .filter(ListOption.opt_default == True).first() if option: default_id = option.id else: default_id = '' list_schema = c.SchemaNode(c.Str(), title=title, name='option', widget=d.widget.RadioChoiceWidget( template='form_radio_choice', values=values), description=self.field.description, opt_default=default_id, parent_id=self.field.id, **req_dict) elif list_type == 'checkbox': def_options = sas.query(ListOption) \ .filter(ListOption.field_id == self.field.id) \ .filter(ListOption.opt_default == True).all() list_schema = c.SchemaNode(d.Set(allow_empty=True), title=title, name='option', widget=d.widget.CheckboxChoiceWidget(values=values, template='form_checkbox_choice'), defaults=options_id, description=self.field.description, parent_id=self.field.id, **req_dict) list_map_schema.add(list_schema) if self.field.get_option('new_option') == 'true': other_option_label = self.field.get_option('new_option_label') other_schema_args = dict( title='' , name='other' , default='' , missing='' , widget=d.widget.TextInputWidget( template='form_other' , category='structural') , other_label=other_option_label , list_type=list_type , parent_id=self.field.id) other_option = c.SchemaNode(c.Str(), **other_schema_args) list_map_schema.add(other_option) return list_map_schema
class Labels(col.SequenceSchema): label = col.SchemaNode(col.Str())
class BadRequestSchema(colander.MappingSchema): message = colander.SchemaNode(colander.Str(), description='Bad request message') status = colander.SchemaNode(colander.Str(), description='Status code message')
class ActivateSchema(c.Schema): """Activate schema. Activation code is used to activate the account """ code = c.SchemaNode(c.Str(), required=True)
class InternalServerErrorSchema(colander.MappingSchema): error = colander.SchemaNode(colander.Str(), description='Error message') status = colander.SchemaNode(colander.Str(), description='Status code message')
class LoginFormSchema(colander.MappingSchema): login = colander.SchemaNode(TypeUser()) password = colander.SchemaNode(colander.Str(), widget=deform.widget.PasswordWidget())
class FlightQuerystringSchema(colander.MappingSchema): origin = colander.SchemaNode(colander.Str()) destination = colander.SchemaNode(colander.Str())