From d761c34e8ba0e5ff79a34ff7ba40569f977c11dc Mon Sep 17 00:00:00 2001 From: narzeja Date: Sat, 15 Oct 2016 21:53:51 +0200 Subject: [PATCH] basic blueprint functionality --- sanic/blueprints.py | 74 ++++++++++++++++++++++++++++++++++++--------- 1 file changed, 59 insertions(+), 15 deletions(-) diff --git a/sanic/blueprints.py b/sanic/blueprints.py index dd009ce6..585863bb 100644 --- a/sanic/blueprints.py +++ b/sanic/blueprints.py @@ -1,24 +1,68 @@ -from sanic import Sanic -from sanic import Blueprint -from sanic.response import json, text -app = Sanic(__name__) -blueprint = Blueprint('name', url_prefix='/my_blueprint') -blueprint2 = Blueprint('name2', url_prefix='/my_blueprint2') +class BlueprintSetup(): + """ + """ + + def __init__(self, blueprint, app, options): + self.app = app + self.blueprint = blueprint + self.options = options + + url_prefix = self.options.get('url_prefix') + if url_prefix is None: + url_prefix = self.blueprint.url_prefix + + #: The prefix that should be used for all URLs defined on the + #: blueprint. + self.url_prefix = url_prefix + + def add_url_rule(self, uri, methods=None, handler=None, **options): + """A helper method to register a handler to the application url routes. + + """ + if self.url_prefix: + uri = self.url_prefix + uri + + self.app.router.add(uri, methods, handler) -@blueprint.route('/foo') -async def foo(request): - return json({'msg': 'hi from blueprint'}) +class Blueprint(): + def __init__(self, name, url_prefix=None): + self.name = name + self.url_prefix = url_prefix + self.deferred_functions = [] + + def record(self, func): + """Registers a callback function that is invoked when the blueprint is + registered on the application. + + """ + self.deferred_functions.append(func) -@blueprint2.route('/foo') -async def foo2(request): - return json({'msg': 'hi from blueprint2'}) + def make_setup_state(self, app, options): + """ + """ + return BlueprintSetup(self, app, options) + def register(self, app, options): + """ + """ + state = self.make_setup_state(app, options) + for deferred in self.deferred_functions: + deferred(state) -app.register_blueprint(blueprint) -app.register_blueprint(blueprint2) + def route(self, uri, methods=None): + """ + """ + def decorator(handler): + self.add_url_rule(uri=uri, methods=methods, handler=handler) + return handler + return decorator -app.run(host="0.0.0.0", port=8000, debug=True) + def add_url_rule(self, uri, methods=None, handler=None): + """ + """ + self.record(lambda s: + s.add_url_rule(uri, methods, handler))