From ad7abf7bc3b4d93100190b1c923a521f0a03a5e6 Mon Sep 17 00:00:00 2001 From: 38elements Date: Tue, 2 May 2017 01:27:55 +0900 Subject: [PATCH] Blueprint.add_route() for instance method --- sanic/blueprints.py | 10 ++++++++-- tests/test_blueprints.py | 18 ++++++++++++++++++ 2 files changed, 26 insertions(+), 2 deletions(-) diff --git a/sanic/blueprints.py b/sanic/blueprints.py index 7e9953e0..ce048cba 100644 --- a/sanic/blueprints.py +++ b/sanic/blueprints.py @@ -1,4 +1,5 @@ from collections import defaultdict, namedtuple +from types import MethodType from sanic.constants import HTTP_METHODS from sanic.views import CompositionView @@ -121,9 +122,14 @@ class Blueprint: if isinstance(handler, CompositionView): methods = handler.handlers.keys() + _handler = handler + if isinstance(handler, MethodType): + def _handler(*args, **kwargs): + return handler(*args, **kwargs) + self.route(uri=uri, methods=methods, host=host, - strict_slashes=strict_slashes)(handler) - return handler + strict_slashes=strict_slashes)(_handler) + return _handler def websocket(self, uri, host=None, strict_slashes=False): """Create a blueprint websocket route from a decorated function. diff --git a/tests/test_blueprints.py b/tests/test_blueprints.py index 46726836..2ca687be 100644 --- a/tests/test_blueprints.py +++ b/tests/test_blueprints.py @@ -349,3 +349,21 @@ def test_bp_shorthand(): 'Sec-WebSocket-Version': '13'}) assert response.status == 101 assert ev.is_set() + + +def test_blueprint_handler_is_instance_method(): + + blueprint = Blueprint('test_blueprint_handler_is_instance_method') + + class Foo(): + + def handler(self, request): + return text('OK') + + foo = Foo() + app = Sanic('test_blueprint_handler_is_instance_method') + blueprint.add_route(foo.handler, '/get') + app.blueprint(blueprint) + + request, response = app.test_client.get('/get') + assert response.text == 'OK'