Blueprint support, with docs, example, and tests

This commit is contained in:
narzeja
2016-10-15 21:38:12 +02:00
parent 4153028096
commit aaf571fae4
6 changed files with 182 additions and 0 deletions

View File

@@ -1 +1,2 @@
from .sanic import Sanic
from .blueprints import Blueprint

24
sanic/blueprints.py Normal file
View File

@@ -0,0 +1,24 @@
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')
@blueprint.route('/foo')
async def foo(request):
return json({'msg': 'hi from blueprint'})
@blueprint2.route('/foo')
async def foo2(request):
return json({'msg': 'hi from blueprint2'})
app.register_blueprint(blueprint)
app.register_blueprint(blueprint2)
app.run(host="0.0.0.0", port=8000, debug=True)

View File

@@ -85,6 +85,23 @@ class Sanic:
return middleware
def register_blueprint(self, blueprint, **options):
"""
Registers a blueprint on the application.
:param blueprint: Blueprint object
:param options: option dictionary with blueprint defaults
:return: Nothing
"""
if blueprint.name in self.blueprints:
assert self.blueprints[blueprint.name] is blueprint, \
'A blueprint\'s name collision occurred between %r and ' \
'%r. Both share the same name "%s". ' % \
(blueprint, self.blueprints[blueprint.name], blueprint.name)
else:
self.blueprints[blueprint.name] = blueprint
self._blueprint_order.append(blueprint)
blueprint.register(self, options)
# -------------------------------------------------------------------- #
# Request Handling
# -------------------------------------------------------------------- #