阿吉的Sanic教程--15類視圖

15. 類視圖

基本類視圖是一個發送響應給請求的類。它提供了一個不同的處理方法給相同的路由請求。和開發者自定的裝飾器和和處理函數不同的是,使用類視圖處理url可以將爲每一個url指定請求方式。

(1)定義類視圖

基類是HTTPMethodView的一個子類,開發者可以爲每個路由限制請求方式,將如請求路由所對應的視圖函數沒有定義請求方法,會返回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('some_name')

class SimpleView(HTTPMethodView):

  def get(self, request):
      return text('I am get method')

  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(), '/')

開發者可以使用async 語法

from sanic import Sanic
from sanic.views import HTTPMethodView
from sanic.response import text

app = Sanic('some_name')

class SimpleAsyncView(HTTPMethodView):

  async def get(self, request):
      return text('I am async get method')

app.add_route(SimpleAsyncView.as_view(), '/')

(2)url參數

假如在url中傳遞參數,和之前的講解一樣,具體示例如下所示:

class NameView(HTTPMethodView):

  def get(self, request, name):
    return text('Hello {}'.format(name))

app.add_route(NameView.as_view(), '/<name>')

(3)裝飾器

開發者如果想要使用裝飾器類,可以使用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")

(4)URL的構建

假如開發者希望使用HttpMethodView構建url,使用名字類的名字進行傳遞,具體示例如下所示:

@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')

(5)使用自定義視圖

如果開發者要在HTTPMethodview和CompositionView中做選擇,開發者可以使用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, '/')
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章