class LoginSchema(Schema): allow_extra_fields = True filter_extra_fields = True firstname = String(not_empty=True) lastname = String(not_empty=True) email = String(not_empty=True) otherseries = String()
class ConfigFrontend(Schema): """Configuration validator for the front-end service.""" if_key_missing = None port = Int(min=1, max=65535, if_missing=8001) prefix = String(if_missing=None) interface = String(if_missing=None)
class ConfigTFTP(Schema): """Configuration validator for the TFTP service.""" if_key_missing = None root = String(if_missing="/var/lib/maas/tftp") port = Int(min=1, max=65535, if_missing=69) generator = String(if_missing=b"http://localhost/MAAS/api/1.0/pxeconfig/")
def test_sv_min(): sv = String(min=2, accept_python=False) assert sv.to_python("foo") == "foo" assert validate(sv, "x") == messages('tooShort', None, min=2) assert validate(sv, None) == messages('empty', None) # should be completely invalid? assert validate(sv, []) == messages('empty', None, min=2) assert sv.from_python(['x', 'y']) == 'x, y'
class ReviewSchema(Schema): filter_extra_fields = True allow_extra_fields = True name = String(not_empty=True) stars = Number(not_empty=True) statement = String(not_empty=True) description = String(not_empty=True)
class ConfigOops(Schema): """Configuration validator for OOPS options.""" if_key_missing = None directory = String(if_missing=b"") reporter = String(if_missing=b"LONGPOLL") chained_validators = (RequireIfPresent("reporter", present="directory"), )
class ConfigBroker(Schema): """Configuration validator for message broker options.""" if_key_missing = None host = String(if_missing=b"localhost") port = Int(min=1, max=65535, if_missing=5672) username = String(if_missing=b"guest") password = String(if_missing=b"guest") vhost = String(if_missing="/")
class EventSchema(Schema): allow_extra_fields = True filter_extra_fields = True name = String(not_empty=True) date = SDate() location = String() sponsor = String() host = String() designer = String() chair = String() practice = Bool() ispro = Bool() courses = Int(min=1, not_empty=True) runs = Int(min=1, not_empty=True) countedruns = Int(if_empty=0) conepen = Number(if_empty=2.0) gatepen = Number(if_empty=10.0) segments = String() regopened = SDateTime() regclosed = SDateTime() perlimit = Int(min=1) doublespecial = Bool() totlimit = Int(min=0) paypal = String() cost = Int() notes = String()
class FaseFormValidator(Schema): nombre = All( String(min=4, max=32, messages={ 'tooShort': 'Nombre de fase incorrecto, minimo 4 caracteres', 'tooLong': 'Nombre de fase incorrecto, maximo 32 caracteres' }), NotEmpty(messages={'empty': 'Ingrese un nombre de fase'})) descripcion = String( max=100, messages={'tooLong': 'Descripcion no debe superar 100 caracteres'})
class ConfigDriver(Schema): """Configuration validator for a driver.""" if_key_missing = None blacklist = String() comment = String() key_binary = ByteString() modaliases = ForEach(String) module = String() package = String() repository = String()
class ProyectoAddFormValidator(Schema): nombre = All( String(min=4, max=32, messages={ 'tooShort': 'Nombre de proyecto incorrecto, minimo 4 caracteres', 'tooLong': 'Nombre de rol incorrecto, maximo 32 caracteres' }), UniqueNewNombre(), NotEmpty(messages={'empty': 'Ingrese un nombre de proyecto'})) descripcion = String( max=200, messages={'tooLong': 'Descripcion no debe superar 200 caracteres'})
class DriverSchema(Schema): allow_extra_fields = True filter_extra_fields = False firstname = String(not_empty=True) lastname = String(not_empty=True) email = String(not_empty=True) address = String() city = String() state = String() zip = String() phone = String() brag = String() sponsor = String()
class ClassSchema(Schema): allow_extra_fields = True filter_extra_fields = True code = String(not_empty=True) descrip = String(not_empty=True) eventtrophy = Bool() champtrophy = Bool() carindexed = Bool() classindex = String() classmultiplier = Number(not_empty=True) usecarflag = Bool() numorder = Int() countedruns = Int(if_empty=0) caridxrestrict = String()
class RolFormValidator(Schema): nombre_rol = All( String(min=4, max=32, messages={ 'tooShort': 'Nombre de rol incorrecto, minimo 4 caracteres', 'tooLong': 'Nombre de rol incorrecto, maximo 32 caracteres' }), NotEmpty(messages={'empty': 'Ingrese un nombre de rol'})) descripcion = String( max=100, messages={'tooLong': 'Descripcion no debe superar 100 caracteres'}) permisos = NotEmpty( messages={"empty": u"Debe seleccionar al menos un permiso"}) permisos_src = NotEmpty( messages={"empty": u"Debe seleccionar al menos un permiso"})
class UsuarioEditFormValidator(UsuarioAddFormValidator): nombre_usuario = None password = None repita_password = None nuevo_password = PasswordChanged() repita_nuevo_password = PasswordChanged() email = All( UniqueEditEmail(), Email(not_empty=True, messages={ 'empty': 'Ingrese una direccion de email', 'noAt': 'Un email debe contener un @', 'badUsername': '******', 'badDomain': 'Ingrese un dominio de email correcto', })) chained_validators = (FieldsMatch( 'nuevo_password', 'repita_nuevo_password', messages={'invalidNoMatch': 'Passwords no coinciden'}), ) nro_documento = All( UniqueEditNroDocumento(), String( min=5, max=50, messages={ 'tooShort': "Nro de Documendo invalido, debe tener 5 digitos como minimo", 'tooLong': "Nro de Documendo invalido", }), NotEmpty(messages={'empty': 'Ingrese numero de documento'}), isInt(messages={'integer': 'Ingrese un numero'}))
class ConfigBootEphemeral(Schema): """Configuration validator for ephemeral boot configuration.""" if_key_missing = None images_directory = String(if_missing="/var/lib/maas/ephemeral") releases = Set(if_missing=None)
class SettingsSchema(Schema): allow_extra_fields = True filter_extra_fields = False seriesname = String(not_empty=True) largestcarnumber = Int(min=99) minevents = Int(if_empty=0) useevents = Int(not_empty=True) sponsorlink = String() pospointlist = String() champsorting = String() superuniquenumbers = Bool() indexafterpenalties = Bool() locked = Bool() usepospoints = Bool() sponsorimage = Validator() seriesimage = Validator() cardimage = Validator()
class EndtoendRevisionSchema(ReportSchema): """Revision Report Schema.""" format = FormatValidator(list=('html', 'json')) starttime = None # no starttime and endtime parameters endtime = None branch_name = BranchNameValidator() revision = String(min=12, max=12) chained_validators = [RequestIdValidator()]
class ProyectoEditFormValidator(ProyectoAddFormValidator): nombre = All( String(min=4, max=32, messages={ 'tooShort': 'Nombre de proyecto incorrecto, minimo 4 caracteres', 'tooLong': 'Nombre de rol incorrecto, maximo 32 caracteres' }), UniqueEditNombre(), NotEmpty(messages={'empty': 'Ingrese un nombre de proyecto'}))
class ReportSchema(Schema): """Base report schema.""" allow_extra_fields = True filter_extra_fields = True format = FormatValidator(list=('html', 'json', 'chart')) tqx = String(if_missing='', if_empty='') starttime = UnixtimestampValidator() endtime = UnixtimestampValidator() chained_validators = [DateCompare(), DateInit(), RequestIdValidator()]
class CopySeriesSchema(Schema): allow_extra_fields = True filter_extra_fields = True name = Regex(r'^(\w)+$') password = String(not_empty=True) settings = Bool() data = Bool() classes = Bool() drivers = Bool() cars = Bool() prevlist = Bool()
class UriData(Schema): """Validate URI data received from CSV or user input. All fields are required, cannot be None and no extra fields are allowed. """ title = String(not_empty=True) URI = URL(not_empty=True) notify = OneOf( ["always", "valid", "invalid"], not_empty=True )
class PasteController(BaseController): def view(self, id, errors=None): """ default pastebin view """ c.highlight = [l for l in get_all_lexers()] c.highlight.sort() c.now = datetime.now() query = model.meta.Session.query(model.Snippet) c.lastsnippets = query.order_by(desc(model.Snippet.creation)).limit(5) if id: c.snippet = query.get(id) or FooSnippet() elif 'id' in request.POST: c.snippet = query.get(request.POST['id']) or FooSnippet() else: c.snippet = FooSnippet() if errors : c.errors = errors else : c.errors = {} return render("/paste.mako") def raw(self, id): """ Raw Pastebin """ query = model.meta.Session.query(model.Snippet) if id: snippet = query.get(id) if snippet: c.raw = snippet.code return render("/raw.mako") abort(404) def post(self): """ form post action (new snippet) """ snippet = model.Snippet() post = request.POST errors = {} # just in case of a better error verification try: snippet.code = UnicodeString().to_python(post['code']) if not snippet.code: errors["code"] = "Required field" except Invalid, e: errors["code"] = "Required field" try: snippet.highlight = String().to_python(post['highlight']) except Invalid, e: pass
class LipishaInitiateSchema(LipishaBaseSchema): api_version = OneOf(LIPISHA_API_VERSIONS, not_empty=True) api_type = OneOf([TYPE_INITIATE], not_empty=True) transaction_date = TimestampValidator(not_empty=True) transaction_amount = Number(not_empty=True) transaction_type = OneOf(LIPISHA_TRANSACTION_TYPES, not_empty=True) transaction_method = String(not_empty=True) transaction_name = String(not_empty=True) transaction_mobile = String(not_empty=True) transaction_paybill = String(not_empty=True) transaction_account = String(not_empty=True) transaction_merchant_reference = String()
class UserForm(Schema): """ Form validation schema for users.""" filter_extra_fields = True allow_extra_fields = True username = UsernamePlainText(min=5, max=16, strip=True) first_name = FirstNameString(not_empty=True, strip=True) last_name = LastNameString(not_empty=True, strip=True) email = Email() password = SecurePassword(min=6, max=80, strip=True) password_confirm = String(strip=True) group_id = Int(not_empty=True) chained_validators = [ FieldsMatch('password', 'password_confirm'), UniqueAuthUsername(), UniqueAuthEmail(), ]
class Config(Schema): """Configuration validator.""" if_key_missing = None oops = ConfigOops broker = ConfigBroker frontend = ConfigFrontend logfile = String(if_empty=b"txlongpoll.log", if_missing=b"txlongpoll.log") @classmethod def parse(cls, stream): """Load a YAML configuration from `stream` and validate.""" return cls.to_python(yaml.load(stream)) @classmethod def load(cls, filename): """Load a YAML configuration from `filename` and validate.""" with open(filename, "rb") as stream: return cls.parse(stream)
def test_sv_string_conversion(): sv = String(not_empty=False) assert sv.from_python(2) == "2" assert sv.from_python([]) == ""
snippet.code = UnicodeString().to_python(post['code']) if not snippet.code: errors["code"] = "Required field" except Invalid, e: errors["code"] = "Required field" try: snippet.highlight = String().to_python(post['highlight']) except Invalid, e: pass snippet.creation = datetime.now() if int(post['expiration']) > 0: snippet.expiration = datetime.fromtimestamp(time() + int(post['expiration'])) else: snippet.expiration = snippet.creation try: snippet.title = String(max=255).to_python(post['title']) if not snippet.title: snippet.title = "Anonymous code" except Invalid, e: snippet.title = "Anonymous code" try: snippet.username = String(max=128).to_python(post['username']) if not snippet.username: snippet.username = "******" except Invalid, e: snippet.title = "Anonymous coward" # slashdot <3 if errors: return self.view(None, errors) if snippet.highlight != "000-GUESS": snippet.codeformatted = highlight(snippet.code, get_lexer_by_name(snippet.highlight.lower()), CodeFormatter())
class UsuarioAddFormValidator(Schema): nombre_usuario = All( String(min=4, max=32, messages={ 'tooShort': 'Nombre de usuario incorrecto, minimo 4 caracteres', 'tooLong': 'Nombre de usuario incorrecto, maximo 32 caracteres' }), UniqueUsername(), NotEmpty(messages={'empty': 'Ingrese un nombre de usuario'})) nombre = All( String(min=2, max=50, messages={ 'tooShort': 'Nombre incorrecto, minimo 2 caracteres', 'tooLong': 'Nombre incorrecto, maximo 50 caracteres' }), NotEmpty(messages={'empty': 'Ingrese un nombre'})) apellido = All( String(min=2, max=50, messages={ 'tooShort': 'Apellido incorrecto, minimo 2 caracteres', 'tooLong': 'Apellido incorrecto, maximo 50 caracteres' }), NotEmpty(messages={'empty': 'Ingrese un apellido'})) password = All( String( min=6, messages={'tooShort': 'Password incorrecto, minimo 6 caracteres'}), NotEmpty(messages={'empty': 'Ingrese password'})) repita_password = All( String( min=6, messages={'tooShort': 'Password incorrecto, minimo 6 caracteres'}), NotEmpty(messages={'empty': 'Ingrese password'})) email = All( UniqueNewEmail(), Email(not_empty=True, messages={ 'empty': 'Ingrese una direccion de email', 'noAt': 'Un email debe contener un @', 'badUsername': '******', 'badDomain': 'Ingrese un dominio de email correcto', })) chained_validators = (FieldsMatch( 'password', 'repita_password', messages={'invalidNoMatch': 'Passwords no coinciden'}), ) nro_documento = All( UniqueNewNroDocumento(), String( min=5, max=50, messages={ 'tooLong': "Nro de Documendo invalido, debe tener 5 digitos como minimo", 'tooShort': "Nro de Documendo invalido", }), NotEmpty(messages={'empty': 'Ingrese numero de documento'}), isInt(messages={'integer': 'Ingrese un numero'})) telefono = All( String( min=6, max=15, messages={ 'tooShort': "Nro de Telefono invalido, debe tener 6 digitos como minimo", 'tooLong': "Nro de Telefono invalido", }), NotEmpty(messages={'empty': 'Ingrese numero de telefono'}), isInt(messages={'integer': 'Ingrese un numero'}))
class IndexSchema(Schema): allow_extra_fields = True filter_extra_fields = True code = String(not_empty=True) descrip = String(not_empty=True) value = Number(not_empty=True)
class DriverFieldSchema(Schema): allow_extra_fields = True filter_extra_fields = True name = String(not_empty=True) title = String(not_empty=True)
class LipishaAcknowledgeSchema(LipishaBaseSchema): api_type = OneOf([TYPE_ACKNOWLEDGE], not_empty=True) transaction_status_code = String(not_empty=True) transaction_status = String(not_empty=True) transaction_status_description = String(not_empty=True)