class based views implementation for sanic
This commit is contained in:
44
docs/class_based_views.md
Normal file
44
docs/class_based_views.md
Normal file
@@ -0,0 +1,44 @@
|
||||
# Class based views
|
||||
|
||||
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 try to use not implemented method, there will be 405 response.
|
||||
|
||||
## Examples
|
||||
```python
|
||||
from sanic import Sanic
|
||||
from sanic.views import MethodView
|
||||
|
||||
app = Sanic('some_name')
|
||||
|
||||
|
||||
class SimpleView(MethodView):
|
||||
|
||||
def get(self, request, *args, **kwargs):
|
||||
return text('I am get method')
|
||||
|
||||
def post(self, request, *args, **kwargs):
|
||||
return text('I am post method')
|
||||
|
||||
def put(self, request, *args, **kwargs):
|
||||
return text('I am put method')
|
||||
|
||||
def patch(self, request, *args, **kwargs):
|
||||
return text('I am patch method')
|
||||
|
||||
def delete(self, request, *args, **kwargs):
|
||||
return text('I am delete method')
|
||||
|
||||
app.add_route(SimpleView(), '/')
|
||||
|
||||
```
|
||||
|
||||
If you need any url params just mention them in method definition:
|
||||
|
||||
```python
|
||||
class NameView(MethodView):
|
||||
|
||||
def get(self, request, name, *args, **kwargs):
|
||||
return text('Hello {}'.format(name))
|
||||
|
||||
app.add_route(NameView(), '/<name')
|
||||
|
||||
```
|
||||
@@ -29,4 +29,16 @@ async def person_handler(request, name):
|
||||
async def folder_handler(request, folder_id):
|
||||
return text('Folder - {}'.format(folder_id))
|
||||
|
||||
async def handler1(request):
|
||||
return text('OK')
|
||||
app.add_route(handler1, '/test')
|
||||
|
||||
async def handler(request, name):
|
||||
return text('Folder - {}'.format(name))
|
||||
app.add_route(handler, '/folder/<name>')
|
||||
|
||||
async def person_handler(request, name):
|
||||
return text('Person - {}'.format(name))
|
||||
app.add_route(handler, '/person/<name:[A-z]>')
|
||||
|
||||
```
|
||||
|
||||
Reference in New Issue
Block a user