How to use the eve.io.mongo.Validator function in Eve

To help you get started, we’ve selected a few Eve 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 marcellmars / letssharebooks / npg / rest-backend / run.py View on Github external
# import time
# def timeit(method):
#     def timed(*args, **kw):
#         ts = time.time()
#         result = method(*args, **kw)
#         te = time.time()
#         print('{} {:.2f} ms'.format(method.__name__, (te - ts) * 1000))
#         return result
#     return timed

# TODO: should be changed in production.
MASTER_SECRET = "874a7f15-0c02-473e-ba2c-c1ef937b9a5c"


class UUIDValidator(Validator):
    def _validate_type_uuid(self, key, value):
        try:
            UUID(value)
        except ValueError:
            pass


class UUIDEncoder(BaseJSONEncoder):
    def default(self, obj):
        if isinstance(obj, UUID):
            return str(obj)
        elif isinstance(obj, ObjectId):
            return str(obj)
        else:
            return super(UUIDEncoder, self).default(obj)
github armadillica / flamenco / flamenco / server-eve / application / __init__.py View on Github external
return False

        node_type_name = self.document['node_type']
        node_type = project_get_node_type(project, node_type_name)
        if node_type is None:
            log.warning('Project %s has no node type %s, declared by node %s',
                        project, node_type_name, self.document.get('_id'))
            self._error(field, 'Unknown node type')
            return False

        try:
            value = self.convert_properties(value, node_type['dyn_schema'])
        except Exception as e:
            log.warning("Error converting form properties", exc_info=True)

        v = Validator(node_type['dyn_schema'])
        val = v.validate(value)

        if val:
            return True

        log.warning('Error validating properties for node %s: %s', self.document, v.errors)
        self._error(field, "Error validating properties")
github KohoVolit / api.parldata.eu / run.py View on Github external
"""Deletes downloaded and stored files related to the entity
	about to be deleted.
	"""
	path = (config.FILES_DIR + '/' + config.URL_PREFIX + '/' +
		resource + '/' + str(document['id']))
	shutil.rmtree(path, ignore_errors=True)


def on_delete_resource_callback(resource):
	"""Deletes all downloaded and stored files related to the resource.
	"""
	path = (config.FILES_DIR + '/' + config.URL_PREFIX + '/' + resource)
	shutil.rmtree(path, ignore_errors=True)


class VpapiValidator(Validator):
	"""Additional validations in the schema.
	"""
	def _validate_format(self, format, field, value):
		"""Validates custom rule `format`.

		No validation is performed for URLs because virtually
		everything is a valid URL according to RFC 3986.
		"""
		if format not in ['partialdate', 'partialdatetime', 'email', 'url']:
			self._error(field, 'Unknown format "{0}"'.format(format))

		partialdate_regex = r'^[0-9]{4}(-[0-9]{2}){0,2}$'
		partialdatetime_regex = r'^[0-9]{4}((-[0-9]{2}){0,2}|(-[0-9]{2}){2}(T[0-9]{2}(:[0-9]{2}(:[0-9]{2})?)?Z)?)$'
		email_regex = r'[^@]+@[^@]+\.[^@]+'

		if format == 'partialdate' and not re.match(partialdate_regex, value) or \
github dfci / matchminer-api / matchminer / validation.py View on Github external
import re

from eve.io.mongo import Validator as EveValidator
from cerberus import Validator as CerberusValidator
from cerberus1 import Validator
from cerberus1 import schema_registry
from matchminer import data_model
from matchminer.database import get_db


class ConsentValidatorEve(EveValidator):

    def _validate_consented(self, consented, field, value):

        # skip if not necessary
        if not consented:
            return

        # run the consent.
        if not check_consent(self.document):
            self._error(field, "Not consented")

    def __signature_exception(self, item):

        signatures = ['mmr_status',
                      'ms_status',
                      'tobacco_signature',
github talkpython / eve-building-restful-mongodb-backed-apis-course / code / validation.py View on Github external
import re

from eve.io.mongo import Validator

class MyValidator(Validator):
    """ You can extend or override the built-in validation rules easily
    by inheriting from the eve.io.mongo.Validator class
    """
    def _validate_isodd(self, isodd, field, value):
        """ Define a brand new 'isodd' rule """
        if isodd and not bool(value & 1):
            self._error(field, 'Value must be an odd number')

    def _validate_type_email(self, field, value):
        """ Extend types by adding a new 'email' type """
        if not re.match(r"[^@]+@[^@]+\.[^@]+", value):
            self._error(field, 'Value is not a valid email address')
github armadillica / pillar / pillar / application / __init__.py View on Github external
from bson import ObjectId
from datetime import datetime
from flask import g
from flask import request
from flask import abort
from eve import Eve

from eve.auth import TokenAuth
from eve.io.mongo import Validator

from application.utils import project_get_node_type

RFC1123_DATE_FORMAT = '%a, %d %b %Y %H:%M:%S GMT'


class ValidateCustomFields(Validator):
    def convert_properties(self, properties, node_schema):
        for prop in node_schema:
            if not prop in properties:
                continue
            schema_prop = node_schema[prop]
            prop_type = schema_prop['type']
            if prop_type == 'dict':
                properties[prop] = self.convert_properties(
                    properties[prop], schema_prop['schema'])
            if prop_type == 'list':
                if properties[prop] in ['', '[]']:
                    properties[prop] = []
                for k, val in enumerate(properties[prop]):
                    if not 'schema' in schema_prop:
                        continue
                    item_schema = {'item': schema_prop['schema']}
github armadillica / pillar / pillar / application / __init__.py View on Github external
return False

        node_type_name = self.document['node_type']
        node_type = project_get_node_type(project, node_type_name)
        if node_type is None:
            log.warning('Project %s has no node type %s, declared by node %s',
                        project, node_type_name, self.document.get('_id'))
            self._error(field, 'Unknown node type')
            return False

        try:
            value = self.convert_properties(value, node_type['dyn_schema'])
        except Exception as e:
            log.warning("Error converting form properties", exc_info=True)

        v = Validator(node_type['dyn_schema'])
        val = v.validate(value)

        if val:
            return True

        log.warning('Error validating properties for node %s: %s', self.document, v.errors)
        self._error(field, "Error validating properties")
github taarifa / TaarifaAPI / taarifa_api / taarifa_api.py View on Github external
from eve import Eve
from eve.io.mongo import Validator
from eve.methods.delete import delete, deleteitem
from eve.methods.post import post_internal
from eve.methods.put import put

from flask import current_app as app
from flask.ext.bootstrap import Bootstrap
from flask.ext.compress import Compress
from eve_docs import eve_docs

from settings import API_NAME, requests, resources


class KeySchemaValidator(Validator):

    def _validate_dynamicschema(self, schema, field, dct):
        """Validate the dictionary `dct` against a schema dynamically read from
        another document of (potentially) another resource.

        A `dynamicschema` has the following fields:

        * ``resource``: resource to load the schema from
        * ``field``: the field name to use in querying the resource (its value
          is taken as the same field in the current document)
        * ``schema``: the field in the retrieved document holding the schema
        * ``transform``: a function to transform the schema (optional)"""
        query = {schema['field']: self.document[schema['field']]}
        res = app.data.find_one(schema['resource'], None, **query)
        if res:
            dynamic_schema = res[schema['schema']]
github armadillica / pillar / pillar / api / custom_field_validation.py View on Github external
from datetime import datetime
import logging

from bson import ObjectId, tz_util
from eve.io.mongo import Validator
from flask import current_app

from pillar import markdown

log = logging.getLogger(__name__)


class ValidateCustomFields(Validator):

    # TODO: split this into a convert_property(property, schema) and call that from this function.
    def convert_properties(self, properties, node_schema):
        """Converts datetime strings and ObjectId strings to actual Python objects."""

        date_format = current_app.config['RFC1123_DATE_FORMAT']

        for prop in node_schema:
            if prop not in properties:
                continue
            schema_prop = node_schema[prop]
            prop_type = schema_prop['type']

            if prop_type == 'dict':
                try:
                    dict_valueschema = schema_prop['schema']
github armadillica / flamenco / flamenco / server-eve / application / __init__.py View on Github external
from bson import ObjectId
from datetime import datetime
from flask import g
from flask import request
from flask import abort
from eve import Eve

from eve.auth import TokenAuth
from eve.io.mongo import Validator

from application.utils import project_get_node_type

RFC1123_DATE_FORMAT = '%a, %d %b %Y %H:%M:%S GMT'


class ValidateCustomFields(Validator):
    def convert_properties(self, properties, node_schema):
        for prop in node_schema:
            if not prop in properties:
                continue
            schema_prop = node_schema[prop]
            prop_type = schema_prop['type']
            if prop_type == 'dict':
                properties[prop] = self.convert_properties(
                    properties[prop], schema_prop['schema'])
            if prop_type == 'list':
                if properties[prop] in ['', '[]']:
                    properties[prop] = []
                for k, val in enumerate(properties[prop]):
                    if not 'schema' in schema_prop:
                        continue
                    item_schema = {'item': schema_prop['schema']}