2016-11-25 07:10:25 +00:00
# Class based views
2016-11-26 06:44:46 +00:00
Sanic has simple class based implementation. You should implement methods(get, post, put, patch, delete) for the class to every HTTP method you want to support. If someone tries to use a method that has not been implemented, there will be 405 response.
2016-11-25 07:10:25 +00:00
## Examples
```python
from sanic import Sanic
2016-11-26 06:44:46 +00:00
from sanic.views import HTTPMethodView
2016-12-23 00:42:05 +00:00
from sanic.response import text
2016-11-25 07:10:25 +00:00
app = Sanic('some_name')
2016-11-26 06:44:46 +00:00
class SimpleView(HTTPMethodView):
2016-11-25 07:10:25 +00:00
2016-11-26 06:44:46 +00:00
def get(self, request):
2016-11-25 07:10:25 +00:00
return text('I am get method')
2016-11-26 06:44:46 +00:00
def post(self, request):
2016-11-25 07:10:25 +00:00
return text('I am post method')
2016-11-26 06:44:46 +00:00
def put(self, request):
2016-11-25 07:10:25 +00:00
return text('I am put method')
2016-11-26 06:44:46 +00:00
def patch(self, request):
2016-11-25 07:10:25 +00:00
return text('I am patch method')
2016-11-26 06:44:46 +00:00
def delete(self, request):
2016-11-25 07:10:25 +00:00
return text('I am delete method')
2017-01-07 04:57:07 +00:00
app.add_route(SimpleView.as_view(), '/')
2016-11-25 07:10:25 +00:00
```
If you need any url params just mention them in method definition:
```python
2016-11-26 06:44:46 +00:00
class NameView(HTTPMethodView):
2016-11-25 07:10:25 +00:00
2016-11-26 06:44:46 +00:00
def get(self, request, name):
2016-11-25 07:10:25 +00:00
return text('Hello {}'.format(name))
2017-01-07 04:57:07 +00:00
app.add_route(NameView.as_view(), '/< name > ')
```
If you want to add decorator for class, you could set decorators variable
```
class ViewWithDecorator(HTTPMethodView):
2017-01-07 05:13:49 +00:00
decorators = [some_decorator_here]
2017-01-07 04:57:07 +00:00
def get(self, request, name):
return text('Hello I have a decorator')
app.add_route(ViewWithDecorator.as_view(), '/url')
2016-11-25 07:10:25 +00:00
```