class MyFormFields(widgets.WidgetsList): #XXX: Since allow_extra_fields should be removed from validators.Schema, # we need a validator for every input-expecting widget name = widgets.TextField(validator=validators.String()) age = widgets.TextField(validator=validators.Int(), default=0) date = widgets.CalendarDatePicker(validator=validators.DateConverter( if_empty=datetime.now()))
class GroupSave(validators.Schema): groupname = validators.All(KnownGroup, validators.String(max=32, min=2)) display_name = validators.NotEmpty owner = KnownUser prerequisite = KnownGroup group_type = ValidGroupType invite_only = validators.Bool()
class AsteriskSave(validators.Schema): targetname = KnownUser asterisk_enabled = validators.OneOf(['0', '1'], not_empty=True) asterisk_pass = validators.All( ValidAsteriskPass, validators.String(min=6, not_empty=True), )
def _guess_validator(self): """Inspect sample option value to guess validator (crude).""" sample_option = self._get_sample_option() if isinstance(sample_option, int): return validators.Int() elif isinstance(sample_option, basestring): return validators.String() else: raise TypeError("Unknown option type in SelectionField: %r" % (sample_option, ))
class UserEditSchema(validators.Schema): """ separate validation schema from the fields definition make it possible to define a more complex schema that involves field dependency or logical operators """ user_name = validators.String(not_empty=True, max=16) status = validators.OneOf(['ENABLED', 'LOCKED', 'DISABLED']) password = validators.UnicodeString(max=50) password_confirm = validators.UnicodeString(max=50) chained_validators = [ validators.FieldsMatch('password', 'password_confirm') ]
class GroupCreate(validators.Schema): name = validators.All( UnknownGroup, validators.String(max=32, min=3), validators.Regex(regex='^[a-z0-9\-_]+$'), ) display_name = validators.NotEmpty owner = validators.All( KnownUser, validators.NotEmpty, ) prerequisite = KnownGroup group_type = ValidGroupType needs_sponsor = validators.Bool() user_can_remove = validators.Bool() invite_only = validators.Bool()
class InputFieldsSchema(validators.Schema): # Regex validator ensures only certain characters are input, essentially alphanumeric with new lines and spaces peptide = validators.All( accesionOrSeq(), validators.String(min=3), validators.Regex( r'^[^\x00-\x09\x0B-\x0C\x0E-\x1F\x21-\x2F\x3A-\x3C\x3F-\x40\x5B-\x5E\x60\x7B\x7D-\x7F]*$' )) enzyme = validators.OneOf([ "Chymotrypsin", "Chymotrypsin Low Specificity", "Trypsin", "Pepsin (ph = 1.3)", "Pepsin (ph >= 2.0)" ]) misses = validators.Int(if_empty=0, min=0, max=50) minlen = validators.Int(if_empty=0, min=0) maxlen = validators.Int(if_empty=1000000000, min=0) minweight = validators.Int(if_empty=500, min=0) maxweight = validators.Int(if_empty=1000000000, min=0)
class MyFields(widgets.WidgetsList): name = widgets.TextField(validator=validators.String(not_empty=True)) comment = widgets.TextField(validator=validators.String())
class YubikeySave(validators.Schema): targetname = KnownUser yubikey_enabled = validators.OneOf(['0', '1'], not_empty=True) yubikey_prefix = validators.String(min=12, max=12, not_empty=True)
class MyRoot(controllers.RootController): [expose()] def index(self): pass def validation_error_handler(self, tg_source, tg_errors, *args, **kw): self.functionname = tg_source.__name__ self.values = kw self.errors = tg_errors return "Error Message" [expose(template="turbogears.tests.simple", allow_json=True)] def test(self): return dict(title="Foobar", mybool=False, someval="niggles") [expose(html="turbogears.tests.simple")] def test_deprecated(self): return dict(title="Oldbar", mybool=False, someval="giggles") [expose()] def invalid(self): return None [expose()] def pos(self, posvalue): self.posvalue = posvalue return "" [expose()] def servefile(self, tg_exceptions=None): self.servedit = True self.serve_exceptions = tg_exceptions return cherrypy.lib.cptools.serveFile( pkg_resources.resource_filename( "turbogears.tests", "test_controllers.py")) [expose(content_type='text/plain')] def basestring(self): return 'hello world' [expose(content_type='text/plain')] def list(self): return ['hello', 'world'] [expose(content_type='text/plain')] def generator(self): yield 'hello' yield 'world' [expose()] def unicode(self): cherrypy.response.headers["Content-Type"] = "text/html" return u'\u00bfHabla espa\u00f1ol?' [expose()] def returnedtemplate(self): return dict(title="Foobar", mybool=False, someval="foo", tg_template="turbogears.tests.simple") [expose()] def returnedtemplate_short(self): return dict(title="Foobar", mybool=False, someval="foo", tg_template="turbogears.tests.simple") [expose(template="turbogears.tests.simple")] def exposetemplate_short(self): return dict(title="Foobar", mybool=False, someval="foo") [expose()] [validate(validators={'value': validators.StringBoolean()})] def istrue(self, value): self.value = value return str(value) istrue = error_handler(validation_error_handler)(istrue) [expose()] [validate(validators={'value': validators.StringBoolean()})] def nestedcall(self, value): return self.istrue(str(value)) [expose()] [validate(validators={'value': validators.StringBoolean()})] def errorchain(self, value): return "No Error" errorchain = error_handler(istrue)(errorchain) [expose(format="json", template="turbogears.tests.simple")] def returnjson(self): return dict(title="Foobar", mybool=False, someval="foo", tg_template="turbogears.tests.simple") [expose(template="turbogears.tests.simple", allow_json=False)] def allowjson(self): return dict(title="Foobar", mybool=False, someval="foo", tg_template="turbogears.tests.simple") [expose(format="json")] def impliedjson(self): return dict(title="Blah") [expose('json')] def explicitjson(self): return dict(title="Blub") [expose(template="turbogears.tests.simple", allow_json=True)] def jsonerror_handler(self): return dict(someval="errors") [expose(allow_json=True)] def jsonerror(self): raise ValueError jsonerror = exception_handler(jsonerror_handler)(jsonerror) [expose(content_type="xml/atom")] def contenttype(self): return "Foobar" [expose()] [validate(validators={ "firstname": validators.String(min=2, not_empty=True), "lastname": validators.String()})] def save(self, submit, firstname, lastname="Miller"): self.submit = submit self.firstname = firstname self.lastname = lastname self.fullname = "%s %s" % (self.firstname, self.lastname) return self.fullname save = error_handler(validation_error_handler)(save) class Registration(formencode.Schema): allow_extra_fields = True firstname = validators.String(min=2, not_empty=True) lastname = validators.String() [expose()] [validate(validators=Registration())] def save2(self, submit, firstname, lastname="Miller"): return self.save(submit, firstname, lastname) save2 = error_handler(validation_error_handler)(save2) [expose(template="turbogears.tests.simple")] def useother(self): return dict(tg_template="turbogears.tests.othertemplate") [expose(template="cheetah:turbogears.tests.simplecheetah")] def usecheetah(self): return dict(someval="chimps") rwt_called = 0 def rwt(self, func, *args, **kw): self.rwt_called += 1 func(*args, **kw) [expose(template="turbogears.tests.simple", allow_json=True)] def flash_plain(self): flash("plain") return dict(title="Foobar", mybool=False, someval="niggles") [expose(template="turbogears.tests.simple", allow_json=True)] def flash_unicode(self): flash(u"\xfcnicode") return dict(title="Foobar", mybool=False, someval="niggles") [expose(template="turbogears.tests.simple", allow_json=True)] def flash_data_structure(self): flash(dict(uni=u"\xfcnicode", testing=[1, 2, 3])) return dict(title="Foobar", mybool=False, someval="niggles") [expose(template="turbogears.tests.simple", allow_json=True)] def flash_redirect(self): flash(u"redirect \xfcnicode") redirect("/flash_redirected?tg_format=json") [expose(template="turbogears.tests.simple", allow_json=True)] def flash_redirect_with_trouble_chars(self): flash(u"$foo, k\xe4se;\tbar!") redirect("/flash_redirected?tg_format=json") [expose(template="turbogears.tests.simple", allow_json=True)] def flash_redirected(self): return dict(title="Foobar", mybool=False, someval="niggles") def exc_h_value(self, tg_exceptions=None): """Exception handler for the ValueError in raise_value_exc""" return dict(handling_value=True, exception=str(tg_exceptions)) [expose()] def raise_value_exc(self): raise ValueError('Some Error in the controller') raise_value_exc = exception_handler(exc_h_value, "isinstance(tg_exceptions, ValueError)")(raise_value_exc) def exc_h_key(self, tg_exceptions=None): """Exception handler for KeyErrors in raise_all_exc""" return dict(handling_key=True, exception=str(tg_exceptions)) def exc_h_index(self, tg_exceptions=None): """Exception handler for the ValueError in raise_value_exc""" return dict(handling_index=True, exception=str(tg_exceptions)) [expose()] def raise_index_exc(self): raise IndexError('Some IndexError') raise_index_exc = exception_handler(exc_h_index, "isinstance(tg_exceptions, IndexError)")(raise_index_exc) [expose()] def raise_all_exc(self, num=2): num = int(num) if num < 2: raise ValueError('Inferior to 2') elif num == 2: raise IndexError('Equals to 2') elif num > 2: raise KeyError('No such number 2 in the integer range') raise_all_exc = exception_handler(exc_h_index, "isinstance(tg_exceptions, IndexError)")(raise_all_exc) raise_all_exc = exception_handler(exc_h_value, "isinstance(tg_exceptions, ValueError)")(raise_all_exc) raise_all_exc = exception_handler(exc_h_key, "isinstance(tg_exceptions, KeyError)")(raise_all_exc) [expose()] def internal_redirect(self, **kwargs): raise cherrypy.InternalRedirect('/internal_redirect_target') [expose()] def internal_redirect_target(self, **kwargs): return "redirected OK" [expose()] def redirect_to_path_str(self, path): raise redirect(path + '/index') [expose()] def redirect_to_path_list(self, path): raise redirect([path, 'index']) [expose()] def redirect_to_path_tuple(self, path): raise redirect((path, 'index')) [expose()] def redirect_error(self): raise redirect('/foo\r\n')
class Registration(formencode.Schema): allow_extra_fields = True firstname = validators.String(min=2, not_empty=True) lastname = validators.String()