This repository has been archived by the owner on Feb 22, 2024. It is now read-only.
/
flask_jsonschema.py
65 lines (52 loc) · 1.64 KB
/
flask_jsonschema.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
62
63
64
65
# -*- coding: utf-8 -*-
"""
flask_jsonschema
~~~~~~~~~~~~~~~~
flask_jsonschema
"""
import os
from functools import wraps
try:
import simplejson as json
except ImportError:
import json
from flask import current_app, request
from jsonschema import ValidationError, validate
class _JsonSchema(object):
def __init__(self, schemas):
self._schemas = schemas
def get_schema(self, path):
rv = self._schemas[path[0]]
for p in path[1:]:
rv = rv[p]
return rv
class JsonSchema(object):
def __init__(self, app=None):
self.app = app
if app is not None:
self._state = self.init_app(app)
def init_app(self, app):
default_dir = os.path.join(app.root_path, 'jsonschema')
schema_dir = app.config.get('JSONSCHEMA_DIR', default_dir)
schemas = {}
for fn in os.listdir(schema_dir):
key = fn.split('.')[0]
fn = os.path.join(schema_dir, fn)
if os.path.isdir(fn) or not fn.endswith('.json'):
continue
with open(fn) as f:
schemas[key] = json.load(f)
state = _JsonSchema(schemas)
app.extensions['jsonschema'] = state
return state
def validate(self, *path):
def wrapper(fn):
@wraps(fn)
def decorated(*args, **kwargs):
schema = current_app.extensions['jsonschema'].get_schema(path)
validate(request.json, schema)
return fn(*args, **kwargs)
return decorated
return wrapper
def __getattr__(self, name):
return getattr(self._state, name, None)