Sanic官翻-基于类的视图
基于类的视图
基于类的视图只是实现对请求的响应行为的类。它们提供了一种在同一个端点上分隔处理不同HTTP请求类型的方法。可以为终结点分配一个基于类的视图,而不是定义和修饰三个不同的处理函数,每个终结点均针对一个终结点支持的请求类型。
定义视图
基于类的视图应子类化HTTPMethodView
。然后,您可以为要支持的每种HTTP请求类型实现类方法。如果收到没有定义方法的请求,则会生成405:方法不允许响应。
要在端点上注册基于类的视图,请使用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>')
装饰器
如果要将任何装饰器添加到该类,则可以设置装饰器类变量。这些将在调用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")
构建URL
如果希望为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']),第二个参数是处理函数。以下示例显示了既有外部处理函数又有内联lambda的CompositionView用法:
from sanic import Sanic
from sanic.views import CompositionView
from sanic.response import text
app = Sanic(__name__)
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为CompositionView构建URL。