How to use the schema.Schema function in schema

To help you get started, we’ve selected a few schema 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 nerdvegas / rez / src / rez / vendor / schema / test_schema.py View on Github external
def test_validate_file(self):
        assert Schema(
                Use(open)).validate(self.test_file_name).read().startswith('Copyright')
        self.assertRaises(SchemaError, Schema(Use(open)).validate, 'NON-EXISTENT')
        assert Schema(os.path.exists).validate('.') == '.'
        self.assertRaises(SchemaError, Schema(os.path.exists).validate, './non-existent/')
        assert Schema(os.path.isfile).validate(self.test_file_name) == self.test_file_name
        self.assertRaises(SchemaError, Schema(os.path.isfile).validate, 'NON-EXISTENT')
github keleshev / schema / test_schema.py View on Github external
def test_json_schema_or_only_one():
    s = Schema({"test": Or(str, lambda x: len(x) < 5)})
    assert s.json_schema("my-id") == {
        "$schema": "http://json-schema.org/draft-07/schema#",
        "$id": "my-id",
        "properties": {"test": {"type": "string"}},
        "required": ["test"],
        "additionalProperties": False,
        "type": "object",
    }
github ikalnytskyi / holocron / holocron / ext / processors / tags.py View on Github external
        'template': schema.Schema(str),
        'output': schema.Schema(str),
    }
)
def process(app,
            documents,
            *,
            when=None,
            template='index.j2',
            output='tags/{tag}.html'):
    app.metadata['show_tags'] = True

    # map: tag -> [posts]
    tags = collections.defaultdict(list)

    for post in iterdocuments(documents, when):
        if 'tags' in post:
github BobBuildTool / bob / pym / bob / input.py View on Github external
schema.Schema({
                        'path' : str,
                        schema.Optional('libs') : [str],
                        schema.Optional('netAccess') : bool,
                        schema.Optional('environment') : schema.Schema(
                            { varNameSchema : str },
                            error="provideTools: invalid 'environment' property"),
                    })
                )
            }),
            schema.Optional('provideVars') : schema.Schema({
                varNameSchema : str
            }),
            schema.Optional('provideSandbox') : schema.Schema({
                'paths' : [str],
                schema.Optional('mount') : schema.Schema([ MountValidator() ],
                    error="provideSandbox: invalid 'mount' property"),
                schema.Optional('environment') : schema.Schema(
                    { varNameSchema : str },
                    error="provideSandbox: invalid 'environment' property"),
            }),
            schema.Optional('root') : bool,
            schema.Optional('shared') : bool,
            schema.Optional('relocatable') : bool,
            schema.Optional('buildNetAccess') : bool,
            schema.Optional('packageNetAccess') : bool,
        }
        for (name, prop) in self.__properties.items():
            classSchemaSpec[schema.Optional(name)] = schema.Schema(prop.validate,
                error="property '"+name+"' has an invalid type")

        self.__classSchema = schema.Schema(classSchemaSpec)
github CCI-MOC / hil / hil / ext / switches / dell.py View on Github external
def validate(kwargs):
        schema.Schema({
            'username': basestring,
            'hostname': basestring,
            'password': basestring,
        }).validate(kwargs)
github semirook / snaql / snaql / factory.py View on Github external
if kwargs:
                for point, val in kwargs.items():
                    maybe_cond_sql = subrender_cond(name, val, kwargs)
                    if maybe_cond_sql:
                        kwargs[point] = maybe_cond_sql
                    if (
                        isinstance(val, collections.Iterable) and
                        not isinstance(
                            val, (str if PY3K else types.StringTypes, dict)
                        )
                    ):
                        val = [subrender_cond(name, v, kwargs) for v in val]
                        kwargs[point] = [v for v in val if v]

                if 'schema' in kwargs and isinstance(kwargs['schema'], Schema):
                    validation_schema = kwargs.pop('schema')
                    kwargs = validation_schema.validate(kwargs)

                sql_tmpl = (
                    env.from_string(meta_struct['funcs'][name]['raw_sql'])
                )
                return sql_tmpl.render(**kwargs).strip()

            return meta_struct['funcs'][name]['sql']
github carsdotcom / skelebot / skelebot / objects / config.py View on Github external
from .job import Job
from .param import Param
from .skeleYaml import SkeleYaml
from .component import Activation
from ..common import LANGUAGE_IMAGE
from ..components.componentFactory import ComponentFactory

class Config(SkeleYaml):
    """
    Root Config Class for Skelebot YAML File

    Built on top of the SkeleYaml parent Object in order to enherit and extend the functionality
    of yaml file generation and parsing
    """

    schema = Schema({
        'name': And(str, error='\'name\' must be a String'),
        Optional('env'): And(str, error='\'env\' must be a String'),
        Optional('description'): And(str, error='\'description\' must be a String'),
        Optional('maintainer'): And(str, error='\'maintainer\' must be a String'),
        Optional('contact'): And(str, error='\'contact\' must be a String'),
        'language': And(str, error='\'language\' must be a String'),
        Optional('baseImage'): And(str, error='\'baseImage\' must be a String'),
        Optional('primaryJob'): And(str, error='\'primaryJob\' must be a String'),
        Optional('primaryExe'): And(str, Use(str.upper), lambda s: s in ('CMD', 'ENTRYPOINT'), error='\'primaryExe\' must be CMD or ENTRYPOINT'),
        Optional('ephemeral'): And(bool, error='\'ephemeral\' must be a Boolean'),
        Optional('dependencies'): Or(dict, list, error='\'dependencies\' must be a Dict or List'),
        Optional('ignores'): And(list, error='\'ignores\' must be a List'),
        Optional('jobs'): And(list, error='\'jobs\' must be a List'),
        Optional('ports'): And(list, error='\'ports\' must be a List'),
        Optional('components'): And(dict, error='\'components\' must be a Dictionary'),
        Optional('params'): And(list, error='\'params\' must be a List'),
github LookAtMe-Genius-Cameraman / T_System / t_system / remote_ui / api / data_schema.py View on Github external
NETWORK_SCHEMA = Schema({
    'ssid': Use(str),
    'password': Use(str),
})

JOB_SCHEMA = Schema({
    'job_type': And(str, Use(str.lower), lambda s: s in ('track', 'learn', 'secure')),
    'scenario': Or(None, Use(str)),
    'predicted_mission': Use(bool),
    'recognized_persons': Or(None, Use(list)),
    'non_moving_target': Or(None, Use(bool)),
    Optional('arm_expansion'): Or(None, Use(bool)),
    'ai': Or(None, Use(str)),
})

FACE_ENCODING_SCHEMA = Schema({
    'face_name': Use(str),
    'photos': Use(list),
})

UPDATE_SCHEMA = Schema({
    'auto_update': Use(bool),
})

RECORD_SCHEMA = Schema({
    'name': Use(str),
})

ACCESS_SCHEMA = Schema({
    'id': Use(str)
})
github alteryx / promote-python / examples / hello.py View on Github external
@promote.validate_json(Schema({'name': And(str, len)}))
def promoteModel(data):
    return data
github crs4 / notredam / src / dam / kb / tinykb / session.py View on Github external
self.session = sess_or_connstr_or_engine
            except:
                # Something went wrong
                # FIXME: we are masking the actual exception here
                raise TypeError('Unsupported value for Session initialization:'
                                ' %s (type: %s)'
                                % (sess_or_connstr_or_engine,
                                   type(sess_or_connstr_or_engine)))

        if id_ is None:
            id_ = '%x' % (id(self), )
        assert(isinstance(id_, str))
        self._id = id_
        
        if _duplicate_from is None:
            self._schema = kb_schema.Schema(db_prefix)
            self._orm = kb_cls.Classes(self)
        else:
            assert(isinstance(_duplicate_from, Session))
            assert(db_prefix == _duplicate_from._schema.prefix) # Coherency

            self._schema = _duplicate_from._schema
            self._orm = _duplicate_from._orm

        # List of KB classes to be unrealized as soon as the current
        # transaction is committed
        self._kb_classes_pending_unrealize = []

        # Let's use a direct reference in the following closures, in
        # order to avoid capturing 'self' in a reference cycle which
        # may cause memory leaks
        _kb_classes_pending_unrealize = self._kb_classes_pending_unrealize