added as_view

This commit is contained in:
Anton Zhyrney 2017-01-07 06:30:23 +02:00
parent d733c5bb7c
commit fcae4a9f0a
2 changed files with 31 additions and 8 deletions

View File

@ -28,12 +28,35 @@ class HTTPMethodView:
To add the view into the routing you could use
1) app.add_route(DummyView(), '/')
2) app.route('/')(DummyView())
TODO: add doc about devorators
"""
def __call__(self, request, *args, **kwargs):
decorators = ()
def dispatch_request(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)
@classmethod
def as_view(cls, *class_args, **class_kwargs):
""" TODO: add docs
"""
def view(*args, **kwargs):
self = view.view_class(*class_args, **class_kwargs)
return self.dispatch_request(*args, **kwargs)
if cls.decorators:
view.__module__ = cls.__module__
for decorator in cls.decorators:
view = decorator(view)
view.view_class = cls
view.__doc__ = cls.__doc__
view.__module__ = cls.__module__
return view

View File

@ -26,7 +26,7 @@ def test_methods():
def delete(self, request):
return text('I am delete method')
app.add_route(DummyView(), '/')
app.add_route(DummyView.as_view(), '/')
request, response = sanic_endpoint_test(app, method="get")
assert response.text == 'I am get method'
@ -48,7 +48,7 @@ def test_unexisting_methods():
def get(self, request):
return text('I am get method')
app.add_route(DummyView(), '/')
app.add_route(DummyView.as_view(), '/')
request, response = sanic_endpoint_test(app, method="get")
assert response.text == 'I am get method'
request, response = sanic_endpoint_test(app, method="post")
@ -63,7 +63,7 @@ def test_argument_methods():
def get(self, request, my_param_here):
return text('I am get method with %s' % my_param_here)
app.add_route(DummyView(), '/<my_param_here>')
app.add_route(DummyView.as_view(), '/<my_param_here>')
request, response = sanic_endpoint_test(app, uri='/test123')
@ -79,7 +79,7 @@ def test_with_bp():
def get(self, request):
return text('I am get method')
bp.add_route(DummyView(), '/')
bp.add_route(DummyView.as_view(), '/')
app.blueprint(bp)
request, response = sanic_endpoint_test(app)
@ -96,7 +96,7 @@ def test_with_bp_with_url_prefix():
def get(self, request):
return text('I am get method')
bp.add_route(DummyView(), '/')
bp.add_route(DummyView.as_view(), '/')
app.blueprint(bp)
request, response = sanic_endpoint_test(app, uri='/test1/')
@ -112,7 +112,7 @@ def test_with_middleware():
def get(self, request):
return text('I am get method')
app.add_route(DummyView(), '/')
app.add_route(DummyView.as_view(), '/')
results = []
@ -145,7 +145,7 @@ def test_with_middleware_response():
def get(self, request):
return text('I am get method')
app.add_route(DummyView(), '/')
app.add_route(DummyView.as_view(), '/')
request, response = sanic_endpoint_test(app)