basic blueprint functionality
This commit is contained in:
parent
17cc2928d0
commit
fb79f747d4
|
@ -1,24 +1,68 @@
|
||||||
from sanic import Sanic
|
|
||||||
from sanic import Blueprint
|
|
||||||
from sanic.response import json, text
|
|
||||||
|
|
||||||
|
|
||||||
app = Sanic(__name__)
|
class BlueprintSetup():
|
||||||
blueprint = Blueprint('name', url_prefix='/my_blueprint')
|
"""
|
||||||
blueprint2 = Blueprint('name2', url_prefix='/my_blueprint2')
|
"""
|
||||||
|
|
||||||
|
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')
|
class Blueprint():
|
||||||
async def foo(request):
|
def __init__(self, name, url_prefix=None):
|
||||||
return json({'msg': 'hi from blueprint'})
|
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')
|
def make_setup_state(self, app, options):
|
||||||
async def foo2(request):
|
"""
|
||||||
return json({'msg': 'hi from blueprint2'})
|
"""
|
||||||
|
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)
|
def route(self, uri, methods=None):
|
||||||
app.register_blueprint(blueprint2)
|
"""
|
||||||
|
"""
|
||||||
|
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))
|
||||||
|
|
Loading…
Reference in New Issue
Block a user