基于类的视图
基于类的视图只是实现对请求的响应行为的类。它们提供了一种在同一端点划分不同HTTP请求类型处理的方法。可以为端点分配一个基于类的视图,而不是定义和修饰三个不同的处理程序函数(每个端点支持的请求类型对应一个处理程序函数)。
定义视图
基于类的视图应该是子类 HTTPMethodView . 然后,可以为要支持的每个HTTP请求类型实现类方法。如果接收到没有定义方法的请求,则 405: Method not allowed 将生成响应。
要在端点上注册基于类的视图,请 app.add_route 使用方法。第一个参数应该是用方法定义的类 as_view 调用,第二个应该是URL端点。
可用的方法有 get , post , put , patch 和 delete . 使用所有这些方法的类如下所示。
from sanic import Sanic
from sanic.views import HTTPMethodView
from sanic.response import text
app = Sanic("class_views_example")
class SimpleView(HTTPMethodView):
def get(self, request):
return text('I am get method')
# You can also use async syntax
async def post(self, request):
return text('I am post method')
def put(self, request):
return text('I am put method')
def patch(self, request):
return text('I am patch method')
def delete(self, request):
return text('I am delete method')
app.add_route(SimpleView.as_view(), '/')
URL参数
如果您需要任何URL参数(如《路由指南》中所述),请将它们包括在方法定义中。
class NameView(HTTPMethodView):
def get(self, request, name):
return text('Hello {}'.format(name))
app.add_route(NameView.as_view(), '/<name>')
装饰者
如果要向类中添加任何装饰器,可以设置 decorators 类变量。当 as_view 被称为。
class ViewWithDecorator(HTTPMethodView):
decorators = [some_decorator_here]
def get(self, request, name):
return text('Hello I have a decorator')
def post(self, request, name):
return text("Hello I also have a decorator")
app.add_route(ViewWithDecorator.as_view(), '/url')
但是如果你只想装饰一些功能,而不是所有的功能,你可以这样做:
class ViewWithSomeDecorator(HTTPMethodView):
@staticmethod
@some_decorator_here
def get(request, name):
return text("Hello I have a decorator")
def post(self, request, name):
return text("Hello I don't have any decorators")
网址构建
如果您希望为HTTPMethodView构建一个URL,请记住类名将是您要传递到的端点 url_for . 例如:
@app.route('/')
def index(request):
url = app.url_for('SpecialClassView')
return redirect(url)
class SpecialClassView(HTTPMethodView):
def get(self, request):
return text('Hello from the Special Class View!')
app.add_route(SpecialClassView.as_view(), '/special_class_view')
使用合成视图
作为 HTTPMethodView ,你可以使用 CompositionView 将处理程序函数移到视图类之外。
每个支持的HTTP方法的处理程序函数在源中的其他地方定义,然后使用 CompositionView.add 方法。第一个参数是要处理的HTTP方法列表(例如。 ['GET', 'POST'] ),第二个是处理函数。下面的示例显示 CompositionView 与外部处理程序函数和内联lambda一起使用:
from sanic import Sanic
from sanic.views import CompositionView
from sanic.response import text
app = Sanic("composition_example")
def get_handler(request):
return text('I am a get method')
view = CompositionView()
view.add(['GET'], get_handler)
view.add(['POST', 'PUT'], lambda request: text('I am a post/put method'))
# Use the new view to handle requests to the base URL
app.add_route(view, '/')
注意:当前不能使用 url_for .