How to use the colander.MappingSchema function in colander

To help you get started, we’ve selected a few colander 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 Cornices / cornice / tests / validationapp.py View on Github external
    @foobar.post(schema=RequestSchema(), validators=(colander_validator,))
    def foobar_post(request):
        return {"test": "succeeded"}

    class StringSequence(SequenceSchema):
        _ = SchemaNode(String())

    class ListQuerystringSequence(MappingSchema):
        field = StringSequence()

        def deserialize(self, cstruct):
            if 'field' in cstruct and not isinstance(cstruct['field'], list):
                cstruct['field'] = [cstruct['field']]
            return MappingSchema.deserialize(self, cstruct)

    class QSSchema(MappingSchema):
        querystring = ListQuerystringSequence()


    @foobaz.get(schema=QSSchema(), validators=(colander_validator,))
    def foobaz_get(request):
        return {"field": request.validated['querystring']['field']}

    class NewsletterSchema(MappingSchema):
        email = SchemaNode(String(), validator=Email(), missing=drop)

    class RefererSchema(MappingSchema):
        ref = SchemaNode(Integer(), missing=drop)

    class NewsletterPayload(MappingSchema):
        body = NewsletterSchema()
        querystring = RefererSchema()
github AppEnlight / appenlight / backend / src / appenlight / validators.py View on Github external
missing="unknown",
    )
    metrics = ViewRequestStatsSchema()


class ViewMetricListSchema(colander.SequenceSchema):
    """
    Validates view breakdown stats objects list
    {metrics key of server/time object}
    """

    view_tuple = ViewMetricTupleSchema()
    validator = colander.Length(1)


class ViewMetricSchema(colander.MappingSchema):
    """
    Validates server/timeinterval object, ie:
    {server/time object}

    """

    timestamp = colander.SchemaNode(NonTZDate(), validator=limited_date, missing=None)
    server = colander.SchemaNode(
        colander.String(),
        preparer=[shortener_factory(128), lambda x: x or "unknown"],
        missing="unknown",
    )
    metrics = ViewMetricListSchema()


class GeneralMetricSchema(colander.MappingSchema):
github Kinto / kinto / kinto / plugins / openid / views.py View on Github external
"400": ErrorResponseSchema(description="The request is invalid."),
}


def provider_validator(request, **kwargs):
    """
    This validator verifies that the validator in URL (eg. /openid/auth0/login)
    is a configured OpenIDConnect policy.
    """
    provider = request.matchdict["provider"]
    used = request.registry.settings.get("multiauth.policy.%s.use" % provider, "")
    if not used.endswith("OpenIDConnectPolicy"):
        request.errors.add("path", "provider", "Unknow provider %r" % provider)


class LoginQuerystringSchema(colander.MappingSchema):
    """
    Querystring schema for the login endpoint.
    """

    callback = URL()
    scope = colander.SchemaNode(colander.String())
    prompt = colander.SchemaNode(
        colander.String(), validator=colander.Regex("none"), missing=colander.drop
    )


class LoginSchema(colander.MappingSchema):
    querystring = LoginQuerystringSchema()


login = Service(
github Cornices / cornice.ext.swagger / cornice_swagger / swagger.py View on Github external
def _is_colander_schema(self, args):
        schema = args.get('schema')
        return (isinstance(schema, colander.Schema) or
                (inspect.isclass(schema)
                and issubclass(schema, colander.MappingSchema)))
github Kinto / kinto / kinto / core / resource / schema.py View on Github external
    @staticmethod
    def schema_type():
        return colander.Mapping(unknown="raise")


class JsonPatchBodySchema(colander.SequenceSchema):
    """Body used with JSON Patch (application/json-patch+json) as in RFC 6902."""

    operations = JsonPatchOperationSchema(missing=colander.drop)


# Request schemas


class RequestSchema(colander.MappingSchema):
    """Base schema for kinto requests."""

    @colander.deferred
    def header(node, kwargs):
        return kwargs.get("header")

    @colander.deferred
    def querystring(node, kwargs):
        return kwargs.get("querystring")

    def after_bind(self, node, kw):
        # Set default bindings
        if not self.get("header"):
            self["header"] = HeaderSchema()
        if not self.get("querystring"):
            self["querystring"] = QuerySchema()
github paasmaker / paasmaker / paasmaker / heart / runtime / shell.py View on Github external
import re
import uuid
import tempfile
import time

import paasmaker
from base import BaseRuntime, BaseRuntimeTest

import colander
import tornado

class ShellRuntimeOptionsSchema(colander.MappingSchema):
	# No options.
	pass

class ShellRuntimeParametersSchema(colander.MappingSchema):
	launch_command = colander.SchemaNode(colander.String(),
		title="Launch command",
		description="The command to launch the instance. Substitutes %(port)d with the allocated port.")
	start_timeout = colander.SchemaNode(colander.Integer(),
		title="Startup timeout",
		description="The maximum time to wait for the application to start listening on it's assigned port.",
		missing=20,
		default=20)
	standalone_wait = colander.SchemaNode(colander.Integer(),
		title="Standalone Wait",
		description="For standalone instances, wait this long for the instance to start before considering it running.",
		missing=5,
		default=5)

class ShellEnvironmentParametersSchema(colander.MappingSchema):
	# No options.
github liqd / adhocracy3 / src / adhocracy_mercator / adhocracy_mercator / sheets / mercator2.py View on Github external
class ProjectStatusEnum(AdhocracySchemaNode):
    """Enum of organizational statuses."""

    schema_type = colander.String
    default = 'other'
    missing = colander.required
    validator = colander.OneOf(['starting',
                                'developing',
                                'scaling',
                                'other',
                                ])


class StatusSchema(colander.MappingSchema):
    status = ProjectStatusEnum(missing=colander.required)


status_meta = sheet_meta._replace(
    isheet=IStatus,
    schema_class=StatusSchema,
)


class IChallenge(ISheet):
    """Marker interface for the challenge in the road to impact section."""


class ChallengeSchema(colander.MappingSchema):
    """Datastruct for the challenge field."""
github ANCIR / grano / grano / logic / relations.py View on Github external
import logging
import colander

from grano.core import db, celery
from grano.model import Relation
from grano.logic import properties as properties_logic
from grano.logic.references import ProjectRef, AccountRef
from grano.logic.references import SchemaRef, EntityRef
from grano.plugins import notify_plugins


log = logging.getLogger(__name__)


class RelationBaseValidator(colander.MappingSchema):
    author = colander.SchemaNode(AccountRef())
    project = colander.SchemaNode(ProjectRef())


def validate(data, relation):
    """ Due to some fairly weird interdependencies between the different elements
    of the model, validation of relations has to happen in three steps. """

    validator = RelationBaseValidator()
    sane = validator.deserialize(data)
    project = sane.get('project')

    schema_validator = colander.SchemaNode(colander.Mapping())
    schema_validator.add(colander.SchemaNode(SchemaRef(project),
                         name='schema'))
    schema_validator.add(colander.SchemaNode(EntityRef(project=project),
github paasmaker / paasmaker / paasmaker / common / job / prepare / sourcescm.py View on Github external
#
# Paasmaker - Platform as a Service
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
#

import paasmaker
from ..base import BaseJob
from paasmaker.util.plugin import MODE

import colander

class SourceSCMJobParametersSchema(colander.MappingSchema):
	scm_name = colander.SchemaNode(colander.String())
	scm_parameters = colander.SchemaNode(colander.Mapping(unknown='preserve'))

class SourceSCMJob(BaseJob):
	"""
	A job to fetch source code from an SCM, so it can be read and prepared.
	"""
	MODES = {
		MODE.JOB: SourceSCMJobParametersSchema()
	}

	def start_job(self, context):
		self.context = context
		try:
			self.scm_plugin = self.configuration.plugins.instantiate(
				self.parameters['scm_name'],
github paasmaker / paasmaker / paasmaker / heart / startup / filesystemlinker.py View on Github external
#

import os
import json
import glob
import tempfile

import paasmaker
from paasmaker.pacemaker.prepare.base import BasePrepare, BasePrepareTest

import colander

class FilesystemLinkerConfigurationSchema(colander.MappingSchema):
	pass

class FilesystemLinkerParametersSchema(colander.MappingSchema):
	directories = colander.SchemaNode(
		colander.Sequence(),
		colander.SchemaNode(colander.String()),
		title="Directories",
		description="List of directories to be symlinked into a persistent filesystem location."
	)

class FilesystemLinker(BasePrepare):
	"""
	Does some stuff.

	Make sure you supply relative paths. If you have multiple entries where one is a child
	directory of another, list the parent first and the child second.

	This plugin depends on the application having one (and only one) filesystem service
	allocated to it in the application manifest.