-
Notifications
You must be signed in to change notification settings - Fork 40
/
ext.py
294 lines (241 loc) · 9.79 KB
/
ext.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
# -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2015, 2016, 2017 CERN.
#
# Invenio is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Invenio is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Invenio; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307, USA.
#
# In applying this license, CERN does not
# waive the privileges and immunities granted to it by virtue of its status
# as an Intergovernmental Organization or submit itself to any jurisdiction.
"""Invenio module for building and serving JSONSchemas."""
from __future__ import absolute_import, print_function
import json
import os
import pkg_resources
import six
from flask import request
from jsonref import JsonRef
from six.moves.urllib.parse import urlsplit
from werkzeug.exceptions import HTTPException
from werkzeug.routing import Map, Rule
from werkzeug.utils import cached_property, import_string
from . import config
from .errors import JSONSchemaDuplicate, JSONSchemaNotFound
from .views import create_blueprint
try:
from functools import lru_cache
except ImportError:
from functools32 import lru_cache
class InvenioJSONSchemasState(object):
"""InvenioJSONSchemas state and api."""
def __init__(self, app):
"""Constructor.
:param app: application registering this state
"""
self.app = app
self.schemas = {}
self.url_map = Map([Rule(
'{0}/<path:path>'.format(self.app.config['JSONSCHEMAS_ENDPOINT']),
endpoint='schema',
host=self.app.config['JSONSCHEMAS_HOST'],
)], host_matching=True)
def register_schemas_dir(self, directory):
"""Recursively register all json-schemas in a directory.
:param directory: directory path.
"""
for root, dirs, files in os.walk(directory):
dir_path = os.path.relpath(root, directory)
if dir_path == '.':
dir_path = ''
for file_ in files:
if file_.lower().endswith(('.json')):
schema_name = os.path.join(dir_path, file_)
if schema_name in self.schemas:
raise JSONSchemaDuplicate(
schema_name,
self.schemas[schema_name],
directory
)
self.schemas[schema_name] = os.path.abspath(directory)
def register_schema(self, directory, path):
"""Register a json-schema.
:param directory: root directory path.
:param path: schema path, relative to the root directory.
"""
self.schemas[path] = os.path.abspath(directory)
def get_schema_dir(self, path):
"""Retrieve the directory containing the given schema.
:param path: Schema path, relative to the directory where it was
registered.
:raises invenio_jsonschemas.errors.JSONSchemaNotFound: If no schema
was found in the specified path.
:returns: The schema directory.
"""
if path not in self.schemas:
raise JSONSchemaNotFound(path)
return self.schemas[path]
def get_schema_path(self, path):
"""Compute the schema's absolute path from a schema relative path.
:param path: relative path of the schema.
:raises invenio_jsonschemas.errors.JSONSchemaNotFound: If no schema
was found in the specified path.
:returns: The absolute path.
"""
if path not in self.schemas:
raise JSONSchemaNotFound(path)
return os.path.join(self.schemas[path], path)
@lru_cache(maxsize=1000)
def get_schema(self, path, with_refs=False, resolved=False):
"""Retrieve a schema.
:param path: schema's relative path.
:param with_refs: replace $refs in the schema.
:param resolved: resolve schema using the resolver
:py:const:`invenio_jsonschemas.config.JSONSCHEMAS_RESOLVER_CLS`
:raises invenio_jsonschemas.errors.JSONSchemaNotFound: If no schema
was found in the specified path.
:returns: The schema in a dictionary form.
"""
if path not in self.schemas:
raise JSONSchemaNotFound(path)
with open(os.path.join(self.schemas[path], path)) as file_:
schema = json.load(file_)
if with_refs:
schema = JsonRef.replace_refs(
schema,
base_uri=request.base_url,
loader=self.loader_cls() if self.loader_cls else None,
)
if resolved:
schema = self.resolver_cls(schema)
return schema
def list_schemas(self):
"""List all JSON-schema names.
:returns: list of schema names.
:rtype: list
"""
return self.schemas.keys()
def url_to_path(self, url):
"""Convert schema URL to path.
:param url: The schema URL.
:returns: The schema path or ``None`` if the schema can't be resolved.
"""
parts = urlsplit(url)
try:
loader, args = self.url_map.bind(parts.netloc).match(parts.path)
path = args.get('path')
if loader == 'schema' and path in self.schemas:
return path
except HTTPException:
return None
def path_to_url(self, path):
"""Build URL from a path.
:param path: relative path of the schema.
:returns: The schema complete URL or ``None`` if not found.
"""
if path not in self.schemas:
return None
return self.url_map.bind(
self.app.config['JSONSCHEMAS_HOST'],
url_scheme=self.app.config['JSONSCHEMAS_URL_SCHEME']
).build(
'schema', values={'path': path}, force_external=True)
@cached_property
def loader_cls(self):
"""Loader class used in `JsonRef.replace_refs`."""
cls = self.app.config['JSONSCHEMAS_LOADER_CLS']
if isinstance(cls, six.string_types):
return import_string(cls)
return cls
@cached_property
def resolver_cls(self):
"""Loader to resolve the schema."""
cls = self.app.config['JSONSCHEMAS_RESOLVER_CLS']
if isinstance(cls, six.string_types):
return import_string(cls)
return cls
class InvenioJSONSchemas(object):
"""Invenio-JSONSchemas extension.
Register blueprint serving registered schemas and can be used as an api
to register those schemas.
.. note::
JSON schemas are served as static files. Thus their "id" and "$ref"
fields might not match the Flask application's host and port.
"""
def __init__(self, app=None, **kwargs):
"""Extension initialization.
:param app: The Flask application. (Default: ``None``)
"""
self.kwargs = kwargs
if app:
self.init_app(app, **kwargs)
def init_app(self, app, entry_point_group=None, register_blueprint=True):
"""Flask application initialization.
:param app: The Flask application.
:param entry_point_group: The group entry point to load extensions.
(Default: ``invenio_jsonschemas.schemas``)
"""
self.init_config(app)
if not entry_point_group:
entry_point_group = self.kwargs['entry_point_group'] \
if 'entry_point_group' in self.kwargs \
else 'invenio_jsonschemas.schemas'
state = InvenioJSONSchemasState(app)
# Load the json-schemas from extension points.
if entry_point_group:
for base_entry in pkg_resources.iter_entry_points(
entry_point_group):
directory = os.path.dirname(base_entry.load().__file__)
state.register_schemas_dir(directory)
if register_blueprint:
app.register_blueprint(
create_blueprint(state),
url_prefix=app.config['JSONSCHEMAS_ENDPOINT']
)
self._state = app.extensions['invenio-jsonschemas'] = state
return state
def init_config(self, app):
"""Initialize configuration."""
for k in dir(config):
if k.startswith('JSONSCHEMAS_'):
app.config.setdefault(k, getattr(config, k))
host_setting = app.config['JSONSCHEMAS_HOST']
if not host_setting or host_setting == 'localhost':
app.logger.warning('JSONSCHEMAS_HOST is set to {0}'.format(
host_setting))
def __getattr__(self, name):
"""Proxy to state object."""
return getattr(self._state, name, None)
class InvenioJSONSchemasUI(InvenioJSONSchemas):
"""Invenio-JSONSchemas extension for UI."""
def init_app(self, app):
"""Flask application initialization.
:param app: The Flask application.
"""
return super(InvenioJSONSchemasUI, self).init_app(
app,
register_blueprint=app.config['JSONSCHEMAS_REGISTER_ENDPOINTS_UI']
)
class InvenioJSONSchemasAPI(InvenioJSONSchemas):
"""Invenio-JSONSchemas extension for API."""
def init_app(self, app):
"""Flask application initialization.
:param app: The Flask application.
"""
return super(InvenioJSONSchemasAPI, self).init_app(
app,
register_blueprint=app.config['JSONSCHEMAS_REGISTER_ENDPOINTS_API']
)