dservercore 0.20.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,335 @@
1
+ """dserver Flask app"""
2
+ import logging
3
+ import sys
4
+
5
+ from abc import ABC, abstractmethod
6
+
7
+ from flask import Flask, request
8
+ from flask_cors import CORS
9
+ from flask_smorest import Api
10
+ from flask_smorest import Blueprint as FlaskSmorestBlueprint
11
+ from flask_smorest.pagination import PaginationParameters
12
+ from flask_migrate import Migrate
13
+
14
+ from dservercore.blueprint import Blueprint
15
+ from dservercore.config import Config
16
+ from dservercore.extensions import sql_db, jwt, ma
17
+ from dservercore.schemas import SearchDatasetSchema, RegisterDatasetSchema
18
+ from dservercore.sort import SortParameters
19
+ from dservercore.sql_models import DatasetSchema
20
+
21
+
22
+ from pkg_resources import iter_entry_points
23
+
24
+
25
+ logger = logging.getLogger(__name__)
26
+
27
+ # workaround for diverging python versions:
28
+ try:
29
+ from importlib.metadata import version, PackageNotFoundError
30
+ logger.debug("imported version, PackageNotFoundError from importlib.metadata")
31
+ except ModuleNotFoundError:
32
+ from importlib_metadata import version, PackageNotFoundError
33
+ logger.debug("imported version, PackageNotFoundError from importlib_metadata")
34
+
35
+ # first, try to determine dynamic version at runtime
36
+ try:
37
+ __version__ = version(__name__)
38
+ logger.debug("Determined version %s via importlib_metadata.version", __version__)
39
+ except PackageNotFoundError:
40
+ # if that fails, check for static version file written by setuptools_scm
41
+ try:
42
+ from .version import version as __version__
43
+ logger.debug("Determined version %s from autogenerated dserver_retrieve_plugin/version.py", __version__)
44
+ except:
45
+ logger.debug("All efforts to determine version failed.")
46
+ __version__ = None
47
+
48
+
49
+ class ValidationError(ValueError):
50
+ pass
51
+
52
+
53
+ class AuthenticationError(ValueError):
54
+ pass
55
+
56
+
57
+ class AuthorizationError(ValueError):
58
+ pass
59
+
60
+
61
+ class UnknownBaseURIError(KeyError):
62
+ pass
63
+
64
+
65
+ class UnknownURIError(KeyError):
66
+ pass
67
+
68
+
69
+ class PluginABC(ABC):
70
+ """Common base class for all plugins.
71
+
72
+ There are different groups of plugins, i.e. search plugin, retrieve plugin,
73
+ and extension plugins. These groups differ on where within this lookup
74
+ server core they are hooked to. All of them are discovered via the
75
+ python entrypoints mechanism.
76
+
77
+ Any plugin MUST implement a register_dataset method, and SHOULD implement
78
+ a delete_dataset methods.
79
+ While register_dataset is primarily intended to create new a dataset entry
80
+ (but may as well replace an existing entry), the register_dataset is
81
+ primarily intended to replace an existing entry (but may as well create a
82
+ new entry). register_dataset MUST be idempotent. patch_update_dataset
83
+ SHOULD update an existing entry partially by only modifying specified fields
84
+ and MUST not create new entries. delete_dataset SHOULD remove a dataset
85
+ entry from the plugin's database if applicable.
86
+ """
87
+ @abstractmethod
88
+ def register_dataset(self, dataset_info: RegisterDatasetSchema):
89
+ """Register or update a dataset entry by replacing a possibly existing entry. Idempotent.
90
+
91
+ The base URI is in the dataset_info. It is assumed that preflight checks
92
+ have been made to ensure that the base URI has been registered and that
93
+ the user has permissions to perform the action.
94
+ """
95
+ pass
96
+
97
+ def delete_dataset(self, dataset_uri: str):
98
+ """Delete a dataset from the index by their URI."""
99
+ pass
100
+
101
+ def get_config(self):
102
+ """Return the Config object of the retrieve plugin."""
103
+ return dict()
104
+
105
+ def get_config_secrets_to_obfuscate(self):
106
+ """Return a list of config keys never to be exposed in clear text."""
107
+ return list()
108
+
109
+
110
+ class SearchABC(PluginABC):
111
+ """Any search plugin must inherit from this base class."""
112
+
113
+ @abstractmethod
114
+ def search(self, query : SearchDatasetSchema,
115
+ pagination_parameters: PaginationParameters = None,
116
+ sort_parameters: SortParameters = None) -> DatasetSchema(many=True):
117
+ """Search for datasets.
118
+
119
+ It is assumed that preflight checks have been made to ensure that the
120
+ user has permissions to perform the action and that the base URIs in the
121
+ query have been limited to those the user has permissions to search.
122
+
123
+ The search method is hooked into utils.search_datasets_by_user and
124
+ MUST process a query argument adhering to SearchDatasetSchema,
125
+ meaning
126
+
127
+ {
128
+ "base_uris": [
129
+ "string"
130
+ ],
131
+ "free_text": "string",
132
+ "uuids": [
133
+ "string"
134
+ ],
135
+ "creator_usernames": [
136
+ "string"
137
+ ],
138
+ "tags": [
139
+ "string"
140
+ ]
141
+ }
142
+
143
+ at the time of writing.
144
+
145
+ The search plugin SHOULD make use of "OR" logic for the items in
146
+ "base_uris" and "creator_usernames" lists, but use "AND" logic for
147
+ filtering the search based on the items in the tags list.
148
+
149
+ If pagination and sorting parameters are supplied, the plugin SHOULD
150
+ provide the desired subset of datasets.
151
+ """
152
+ pass
153
+
154
+
155
+ class RetrieveABC(ABC):
156
+ """Any retrieve plugin must inherit from this base class."""
157
+
158
+ @abstractmethod
159
+ def get_readme(self, uri):
160
+ """Return the dataset readme.
161
+
162
+ It is assumed that preflight checks have been made to ensure that the
163
+ user has permissions to access the URI.
164
+ """
165
+ pass
166
+
167
+ @abstractmethod
168
+ def get_manifest(self, uri):
169
+ """Return the dataset manifest.
170
+
171
+ It is assumed that preflight checks have been made to ensure that the
172
+ user has permissions to access the URI.
173
+ """
174
+ pass
175
+
176
+ @abstractmethod
177
+ def get_annotations(self, uri):
178
+ """Return the dataset annotations.
179
+
180
+ It is assumed that preflight checks have been made to ensure that the
181
+ user has permissions to access the URI.
182
+ """
183
+ pass
184
+
185
+ @abstractmethod
186
+ def get_tags(self, uri):
187
+ """Return the dataset tags.
188
+
189
+ It is assumed that preflight checks have been made to ensure that the
190
+ user has permissions to access the URI.
191
+ """
192
+ pass
193
+
194
+
195
+ class ExtensionABC(ABC):
196
+ """Any extension plugin must inherit from this base class.
197
+
198
+ An extension MUST implement:
199
+ - a register_dataset(self, dataset_info) method.
200
+ - a get_config() method.
201
+ - a get_blueprint() method. This also means the extension MUST provide a
202
+ single blueprint.
203
+
204
+ An extension MAY implement
205
+ - an init_app(self, app, *args, **kwargs) method to be called
206
+ from app factory.
207
+
208
+ The app factory will inject extension config parameters into the global
209
+ Flask app config. An extension SHOULD hence:
210
+ - prefix their config parameter keys uniquely, for example with their
211
+ capitalized module name
212
+ - retrieve config parameters in a Flask-typical fashion, i.e.
213
+ from the environment or from file as done within the core at
214
+ dservercore.config.Config
215
+ - provide these parameters via the get_config method.
216
+ - access at runtime via global Flask config, i.e. app.config
217
+ """
218
+
219
+ @abstractmethod
220
+ def get_blueprint(self):
221
+ """Return the Flask blueprint to be used for the extension."""
222
+
223
+ def init_app(self, app, *args, **kwargs):
224
+ """Called by Flask app factory."""
225
+ pass
226
+
227
+
228
+ def create_app(test_config=None):
229
+ app = Flask(__name__)
230
+
231
+ # Load the search plugin.
232
+ search_entrypoints = []
233
+ for entrypoint in iter_entry_points("dservercore.search"):
234
+ logger.info("Discovered search plugin entrypoint %s", entrypoint)
235
+ search_entrypoints.append(entrypoint.load())
236
+ if len(search_entrypoints) < 1:
237
+ raise (RuntimeError("Please install a search plugin"))
238
+ elif len(search_entrypoints) > 1:
239
+ raise (RuntimeError("Too many search plugins; there can be only one"))
240
+ app.search = search_entrypoints[0]()
241
+
242
+ # Load the retrieve plugin.
243
+ retrieve_entrypoints = []
244
+ for entrypoint in iter_entry_points("dservercore.retrieve"):
245
+ logger.info("Discovered retrieve plugin entrypoint %s", entrypoint)
246
+ retrieve_entrypoints.append(entrypoint.load())
247
+ if len(retrieve_entrypoints) < 1:
248
+ raise (RuntimeError("Please install a retrieve plugin"))
249
+ elif len(retrieve_entrypoints) > 1:
250
+ raise (RuntimeError("Too many retrieve plugins; there can be only one"))
251
+ app.retrieve = retrieve_entrypoints[0]()
252
+
253
+ # Load any extension plugins.
254
+ app.custom_extensions = []
255
+ for entrypoint in iter_entry_points("dservercore.extension"):
256
+ logger.info("Discovered extension plugin entrypoint %s", entrypoint)
257
+ ep = entrypoint.load()
258
+ app.custom_extensions.append(ep())
259
+
260
+ # For certain aspects below, search plugin, retrieve plugin, and other extension
261
+ # plugins can be treated on the same level
262
+ app.plugins = [app.search, app.retrieve, *app.custom_extensions]
263
+
264
+ if test_config is None:
265
+ # load the instance config, if it exists, when not testing
266
+ app.config.from_object(Config)
267
+
268
+ # any plugin may provide its own config
269
+ for plugin in app.plugins:
270
+ # if applicable, plugin config is mapped into global flask config
271
+ app.config.from_object(plugin.get_config())
272
+ app.config["CONFIG_SECRETS_TO_OBFUSCATE"].extend(
273
+ plugin.get_config_secrets_to_obfuscate())
274
+
275
+ else:
276
+ # load the test config if passed in
277
+ app.config.from_mapping(test_config)
278
+
279
+ CORS(app)
280
+
281
+ for plugin in app.plugins:
282
+ plugin.init_app(app)
283
+
284
+ app.retrieve.init_app(app)
285
+ app.search.init_app(app)
286
+
287
+ sql_db.init_app(app)
288
+ Migrate(app, sql_db)
289
+ ma.init_app(app)
290
+ jwt.init_app(app)
291
+
292
+ api = Api(app)
293
+
294
+ from dservercore import (
295
+ config_routes,
296
+ uri_routes,
297
+ uuid_routes,
298
+ user_routes,
299
+ me_routes,
300
+ base_uri_routes,
301
+ manifest_routes,
302
+ readme_routes,
303
+ annotations_routes,
304
+ tags_routes,
305
+ )
306
+
307
+ api.register_blueprint(config_routes.bp)
308
+ api.register_blueprint(uri_routes.bp)
309
+ api.register_blueprint(uuid_routes.bp)
310
+ api.register_blueprint(me_routes.bp)
311
+ api.register_blueprint(user_routes.bp)
312
+ api.register_blueprint(base_uri_routes.bp)
313
+ api.register_blueprint(manifest_routes.bp)
314
+ api.register_blueprint(readme_routes.bp)
315
+ api.register_blueprint(annotations_routes.bp)
316
+ api.register_blueprint(tags_routes.bp)
317
+
318
+ # Load dserver extension plugin blueprints.
319
+ for ex in app.custom_extensions:
320
+ bp = ex.get_blueprint()
321
+ if not isinstance(bp, (FlaskSmorestBlueprint, Blueprint)):
322
+ print(
323
+ "Please use flask_smorest.blueprint.Blueprint or dserver.blueprint.Blueprint instead of flask.Blueprint", # NOQA
324
+ file=sys.stderr,
325
+ )
326
+ sys.exit(1)
327
+ api.register_blueprint(bp)
328
+
329
+ @app.before_request
330
+ def log_request():
331
+ """Log the request header in debug mode."""
332
+ app.logger.debug("Request Headers {}".format(request.headers))
333
+ return None
334
+
335
+ return app
@@ -0,0 +1,49 @@
1
+ """Route for retrieving dataset annotations by URI."""
2
+ from flask import (
3
+ abort,
4
+ jsonify,
5
+ current_app
6
+ )
7
+ from flask_jwt_extended import (
8
+ jwt_required,
9
+ get_jwt_identity,
10
+ )
11
+
12
+ from dservercore import UnknownURIError
13
+ from dservercore.blueprint import Blueprint
14
+ from dservercore.schemas import AnnotationSchema
15
+ import dservercore.utils_auth
16
+ from dservercore.utils import (
17
+ url_suffix_to_uri,
18
+ get_annotations_from_uri_by_user
19
+ )
20
+
21
+ bp = Blueprint("annotations", __name__, url_prefix="/annotations")
22
+
23
+
24
+ @bp.route("/<path:uri>", methods=["GET"])
25
+ @bp.response(200, AnnotationSchema)
26
+ @bp.alt_response(401, description="Not registered")
27
+ @bp.alt_response(403, description="No permissions")
28
+ @bp.alt_response(400, description="Unknown URI")
29
+ @jwt_required()
30
+ def annotations(uri):
31
+ """Request the dataset annotations."""
32
+ username = get_jwt_identity()
33
+ if not dservercore.utils_auth.user_exists(username):
34
+ # Unregistered users should see 401.
35
+ abort(401)
36
+
37
+ uri = url_suffix_to_uri(uri)
38
+
39
+ if not dservercore.utils_auth.may_access(username, uri):
40
+ # Authorization errors should return 403.
41
+ abort(403)
42
+
43
+ try:
44
+ annotations = get_annotations_from_uri_by_user(username, uri)
45
+ except UnknownURIError:
46
+ current_app.logger.info("UnknownURIError")
47
+ abort(404)
48
+
49
+ return {"annotations": annotations}
@@ -0,0 +1,153 @@
1
+ """Routes for Base URI management"""
2
+ from flask import (
3
+ abort,
4
+ )
5
+ from flask_jwt_extended import (
6
+ jwt_required,
7
+ get_jwt_identity,
8
+ )
9
+
10
+ from flask_smorest.pagination import PaginationParameters
11
+
12
+ from dservercore.blueprint import Blueprint
13
+ from dservercore.sort import SortParameters, ASCENDING, DESCENDING
14
+ from dservercore.sql_models import BaseURISchema, BaseURIWithPermissionsSchema, BaseURI
15
+ import dservercore.utils_auth
16
+ from dservercore.utils import (
17
+ base_uri_exists,
18
+ get_permission_info,
19
+ register_base_uri,
20
+ delete_base_uri,
21
+ register_permissions,
22
+ url_suffix_to_uri
23
+ )
24
+
25
+ bp = Blueprint("base-uris", __name__, url_prefix="/base-uris")
26
+
27
+
28
+ @bp.route("", methods=["GET"])
29
+ @bp.sort(sort=["+base_uri"], allowed_sort_fields=["base_uri"])
30
+ @bp.paginate()
31
+ @bp.response(200, BaseURISchema(many=True))
32
+ @bp.alt_response(401, description="Not registered")
33
+ @bp.alt_response(403, description="No permissions")
34
+ @jwt_required()
35
+ def base_uris_get(pagination_parameters : PaginationParameters,
36
+ sort_parameters : SortParameters):
37
+ """List all base URIs.
38
+
39
+ The user needs to be admin.
40
+ """
41
+ identity = get_jwt_identity()
42
+
43
+ if not dservercore.utils_auth.user_exists(identity):
44
+ abort(401)
45
+
46
+ if not dservercore.utils_auth.has_admin_rights(identity):
47
+ abort(403)
48
+
49
+ order_by_args = []
50
+ for field, order in sort_parameters.order.items():
51
+ if not hasattr(BaseURI, field):
52
+ continue
53
+ if order == DESCENDING:
54
+ order_by_args.append(getattr(BaseURI, field).desc())
55
+ else: # ascending
56
+ order_by_args.append(getattr(BaseURI, field))
57
+
58
+ query = BaseURI.query.order_by(*order_by_args).filter_by()
59
+ pagination_parameters.item_count = query.count()
60
+ return query.paginate(
61
+ page=pagination_parameters.page,
62
+ per_page=pagination_parameters.page_size,
63
+ error_out=True
64
+ ).items
65
+
66
+
67
+ # per default, route parameters can contain any character except for a forward
68
+ # slash '/' and a period '.'. To include a forward slash in the parameter, you
69
+ # can specify a custom converter for the route parameter, e.g. <path:base_uri>
70
+ @bp.route("/<path:base_uri>", methods=["GET"])
71
+ @bp.response(200, BaseURIWithPermissionsSchema)
72
+ @bp.alt_response(401, description="Not registered")
73
+ @bp.alt_response(403, description="No permissions")
74
+ @bp.alt_response(404, description="Not found")
75
+ @jwt_required()
76
+ def base_uri_get(base_uri):
77
+ """Return base URI information.
78
+
79
+ The user needs to be admin.
80
+ """
81
+ identity = get_jwt_identity()
82
+
83
+ if not dservercore.utils_auth.user_exists(identity):
84
+ abort(401)
85
+
86
+ if not dservercore.utils_auth.has_admin_rights(identity):
87
+ abort(403)
88
+
89
+ base_uri = url_suffix_to_uri(base_uri)
90
+
91
+ if not base_uri_exists(base_uri):
92
+ abort(404)
93
+
94
+ base_uri_data = get_permission_info(base_uri)
95
+ return base_uri_data
96
+
97
+
98
+ @bp.route("/<path:base_uri>", methods=["PUT"])
99
+ @bp.arguments(BaseURIWithPermissionsSchema)
100
+ @bp.response(200)
101
+ @bp.alt_response(201, description="Created")
102
+ @bp.alt_response(401, description="Not registered")
103
+ @bp.alt_response(403, description="No permissions")
104
+ @jwt_required()
105
+ def base_uri_put(permissions : BaseURIWithPermissionsSchema, base_uri):
106
+ """Create or update a base URI in dserver by replacing entry.
107
+
108
+ The user in the Authorization token needs to be admin.
109
+ """
110
+ identity = get_jwt_identity()
111
+
112
+ if not dservercore.utils_auth.user_exists(identity):
113
+ abort(401)
114
+
115
+ if not dservercore.utils_auth.has_admin_rights(identity):
116
+ abort(403)
117
+
118
+ base_uri = url_suffix_to_uri(base_uri)
119
+
120
+ success_code = 200 # updated
121
+ if not base_uri_exists(base_uri):
122
+ register_base_uri(base_uri)
123
+ success_code = 201 # created
124
+
125
+ # put method idempotent
126
+ register_permissions(base_uri, permissions)
127
+
128
+ return "", success_code
129
+
130
+
131
+ @bp.route("/<path:base_uri>", methods=["DELETE"])
132
+ @bp.response(200)
133
+ @bp.alt_response(401, description="Not registered")
134
+ @bp.alt_response(403, description="No permissions")
135
+ @jwt_required()
136
+ def base_uri_delete(base_uri):
137
+ """Delete a base URI from dserver.
138
+
139
+ The user in the Authorization token needs to be admin.
140
+ """
141
+ identity = get_jwt_identity()
142
+
143
+ if not dservercore.utils_auth.user_exists(identity):
144
+ abort(401)
145
+
146
+ if not dservercore.utils_auth.has_admin_rights(identity):
147
+ abort(403)
148
+
149
+ base_uri = url_suffix_to_uri(base_uri)
150
+
151
+ delete_base_uri(base_uri)
152
+
153
+ return "", 200
@@ -0,0 +1,15 @@
1
+ """Custom dserver Blueprint"""
2
+ from flask_smorest.blueprint import Blueprint as FlaskSmorestBlueprint
3
+ from dservercore.sort import SortMixin
4
+
5
+
6
+ class Blueprint(FlaskSmorestBlueprint, SortMixin):
7
+ """Bring together flask-smorest blueprint and custom sort mixin."""
8
+
9
+ def __init__(self, *args, **kwargs):
10
+ self.description = kwargs.pop("description", "")
11
+
12
+ super().__init__(*args, **kwargs)
13
+
14
+ self._prepare_doc_cbks.append(self._prepare_sort_doc)
15
+