class based views implementation for sanic

This commit is contained in:
Anton Zhyrney
2016-11-25 09:10:25 +02:00
parent fc19f2ea34
commit 9f2d73e2f1
9 changed files with 445 additions and 5 deletions

View File

@@ -91,6 +91,12 @@ class Blueprint:
return handler
return decorator
def add_route(self, handler, uri, methods=None):
"""
"""
self.record(lambda s: s.add_route(handler, uri, methods))
return handler
def listener(self, event):
"""
"""

View File

@@ -60,6 +60,17 @@ class Sanic:
return response
def add_route(self, handler, uri, methods=None):
"""
A helper method to register class instance or functions as a handler to the application url routes.
:param handler: function or class instance
:param uri: path of the URL
:param methods: list or tuple of methods allowed
:return: function or class instance
"""
self.route(uri=uri, methods=methods)(handler)
return handler
# Decorator
def exception(self, *exceptions):
"""

View File

@@ -16,7 +16,7 @@ async def local_request(method, uri, cookies=None, *args, **kwargs):
def sanic_endpoint_test(app, method='get', uri='/', gather_request=True,
loop=None, *request_args, **request_kwargs):
loop=None, debug=False, *request_args, **request_kwargs):
results = []
exceptions = []
@@ -34,7 +34,7 @@ def sanic_endpoint_test(app, method='get', uri='/', gather_request=True,
exceptions.append(e)
app.stop()
app.run(host=HOST, port=42101, after_start=_collect_response, loop=loop)
app.run(host=HOST, debug=debug, port=42101, after_start=_collect_response, loop=loop)
if exceptions:
raise ValueError("Exception during request: {}".format(exceptions))

33
sanic/views.py Normal file
View File

@@ -0,0 +1,33 @@
from .exceptions import InvalidUsage
class MethodView:
""" Simple class based implementation of view for the sanic.
You should implement methods(get, post, put, patch, delete) for the class to every HTTP method you want to support.
For example:
class DummyView(View):
def get(self, request, *args, **kwargs):
return text('I am get method')
def put(self, request, *args, **kwargs):
return text('I am put method')
etc.
If someone try use not implemented method, there will be 405 response
If you need any url params just mention them in method definition like:
class DummyView(View):
def get(self, request, my_param_here, *args, **kwargs):
return text('I am get method with %s' % my_param_here)
To add the view into the routing you could use
1) app.add_route(DummyView(), '/')
2) app.route('/')(DummyView())
"""
def __call__(self, request, *args, **kwargs):
handler = getattr(self, request.method.lower(), None)
if handler:
return handler(request, *args, **kwargs)
raise InvalidUsage('Method {} not allowed for URL {}'.format(request.method, request.url), status_code=405)