Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

support view instance for blueprint add_route method #424

Merged
merged 4 commits into from
Feb 14, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions docs/sanic/blueprints.md
Original file line number Diff line number Diff line change
Expand Up @@ -131,8 +131,8 @@ can be used to implement our API versioning scheme.
from sanic.response import text
from sanic import Blueprint

blueprint_v1 = Blueprint('v1')
blueprint_v2 = Blueprint('v2')
blueprint_v1 = Blueprint('v1', url_prefix='/v1')
blueprint_v2 = Blueprint('v2', url_prefix='/v2')

@blueprint_v1.route('/')
async def api_v1_root(request):
Expand Down
23 changes: 19 additions & 4 deletions sanic/blueprints.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
from collections import defaultdict, namedtuple

from sanic.constants import HTTP_METHODS
from sanic.views import CompositionView

FutureRoute = namedtuple('Route', ['handler', 'uri', 'methods', 'host'])
FutureListener = namedtuple('Listener', ['handler', 'uri', 'methods', 'host'])
Expand Down Expand Up @@ -82,15 +84,28 @@ def decorator(handler):
return handler
return decorator

def add_route(self, handler, uri, methods=None, host=None):
def add_route(self, handler, uri, methods=frozenset({'GET'}), host=None):
"""
Creates a blueprint route from a function.
:param handler: Function to handle uri request.
:param handler: Function for handling uri requests. Accepts function,
or class instance with a view_class method.
:param uri: Endpoint at which the route will be accessible.
:param methods: List of acceptable HTTP methods.
:return: function or class instance
"""
route = FutureRoute(handler, uri, methods, host)
self.routes.append(route)
# Handle HTTPMethodView differently
if hasattr(handler, 'view_class'):
methods = set()

for method in HTTP_METHODS:
if getattr(handler.view_class, method.lower(), None):
methods.add(method)

# handle composition view differently
if isinstance(handler, CompositionView):
methods = handler.handlers.keys()

self.route(uri=uri, methods=methods, host=host)(handler)
return handler

def listener(self, event):
Expand Down