-
Notifications
You must be signed in to change notification settings - Fork 12
/
validator.py
61 lines (47 loc) · 2.52 KB
/
validator.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# -*- coding: utf-8 -*-
from openelevationservice.server.api import api_exceptions
from openelevationservice.server.utils import logger
from cerberus import Validator, TypeDefinition
log = logger.get_logger(__name__)
object_type = TypeDefinition("object", (object,), ())
Validator.types_mapping['object'] = object_type
v = Validator()
schema_post = {'geometry': {'anyof_type': ['object', 'list', 'string'], 'required': True},
'format_in': {'type': 'string', 'allowed': ['geojson', 'point', 'encodedpolyline', 'encodedpolyline5', 'encodedpolyline6', 'polyline'], 'required': True},
'format_out': {'type': 'string', 'allowed': ['geojson', 'point', 'encodedpolyline', 'encodedpolyline5', 'encodedpolyline6', 'polyline'], 'default': 'geojson'},
'dataset': {'type': 'string', 'allowed': ['srtm'], 'default': 'srtm'}
}
schema_get = {'geometry': {'type': 'string', 'required': True},
'format_out': {'type': 'string', 'allowed': ['geojson', 'point'], 'default': 'geojson'},
'dataset': {'type': 'string', 'allowed': ['srtm'], 'default': 'srtm'}
}
def validate_request(request):
"""
Validates full request with regards to validation schemas and HTTP headers.
:param request: POST or GET request from user
:type request: Flask request
:raises InvalidUsage: internal HTTP 500 error with more detailed description.
:returns: validated and normalized request arguments
:rtype: dict
"""
if request.method == 'GET':
v.allow_unknown = True
v.validate(dict(request.args), schema_get)
if request.method == 'POST':
if not request.headers.get('Content-Type'):
raise api_exceptions.InvalidUsage(400,
4001,
"Missing Content-Type request header")
if 'application/json' not in request.headers.get('Content-Type'):
raise api_exceptions.InvalidUsage(400,
4001,
"MIME type is not application/json")
v.validate(request.get_json(), schema_post)
if v.errors:
errors = []
for error in v.errors:
errors.append("Argument '{}': {}".format(error, v.errors[error][0]))
raise api_exceptions.InvalidUsage(400,
4000,
", ".join(errors))
return v.document