From ced1f0167027a596e80f7f87d3006ddf7c1e246d Mon Sep 17 00:00:00 2001 From: Gleyberson Andrade Date: Tue, 18 Aug 2020 13:20:07 -0300 Subject: [PATCH] Update APIServer to use Flask blueprints Today, an exception is raised when two or more endpoints are registered with the same name. This commit changes the APIServer class to use Flask blueprints when the napps endpoints are created. --- kytos/core/api_server.py | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/kytos/core/api_server.py b/kytos/core/api_server.py index b14d80d0a..f0a1f37d0 100644 --- a/kytos/core/api_server.py +++ b/kytos/core/api_server.py @@ -12,7 +12,7 @@ from urllib.error import HTTPError, URLError from urllib.request import urlopen, urlretrieve -from flask import Flask, jsonify, request, send_file +from flask import Blueprint, Flask, jsonify, request, send_file from flask_cors import CORS from flask_socketio import SocketIO, join_room, leave_room from werkzeug.exceptions import HTTPException @@ -98,7 +98,8 @@ def register_rest_endpoint(self, url, function, methods): stacklevel=2) if url.startswith('/'): url = url[1:] - self._start_endpoint(f'/kytos/{url}', function, methods=methods) + self._start_endpoint(self.app, f'/kytos/{url}', function, + methods=methods) def start_api(self): """Start this APIServer instance API. @@ -123,7 +124,8 @@ def register_core_endpoint(self, rule, function, **options): Not used by NApps, but controller. """ - self._start_endpoint(self._CORE_PREFIX + rule, function, **options) + self._start_endpoint(self.app, self._CORE_PREFIX + rule, function, + **options) def _register_web_ui(self): """Register routes to the admin-ui homepage.""" @@ -296,10 +298,15 @@ def register_napp_endpoints(self, napp): Args: napp (Napp): Napp instance to register new endpoints. """ + napp_blueprint = Blueprint(napp.napp_id, __name__) + for function in self._get_decorated_functions(napp): for rule, options in function.route_params: absolute_rule = self.get_absolute_rule(rule, napp) - self._start_endpoint(absolute_rule, function, **options) + self._start_endpoint(napp_blueprint, absolute_rule, function, + **options) + + self.app.register_blueprint(napp_blueprint) @staticmethod def _get_decorated_functions(napp): @@ -323,14 +330,14 @@ def get_absolute_rule(cls, rule, napp): # END decorator methods - def _start_endpoint(self, rule, function, **options): + def _start_endpoint(self, app, rule, function, **options): """Start ``function``'s endpoint. Forward parameters to ``Flask.add_url_rule`` mimicking Flask ``@route`` decorator. """ endpoint = options.pop('endpoint', None) - self.app.add_url_rule(rule, endpoint, function, **options) + app.add_url_rule(rule, endpoint, function, **options) self.log.info('Started %s - %s', rule, ', '.join(options.get('methods', self.DEFAULT_METHODS)))