Sanic Response HTTP 響應

veelion發表於2019-03-23

Sanic 生成 HTTP 響應的子模組是 sanic.response。該模組可以生成多種格式的HTTP響應,包括純文字(Plain Text)、HTML、JSON、檔案(File)、資料流(Streaming)、檔案流(File Streaming)、重定向(Redirect)、生資料(Raw)。分別對應該子模組的響應函式:

所有返回的響應都是一個HTTPResponse類(或StreamingHTTPResponse類)的例項。這兩個類都派生自BaseHTTPResponse類。

Sanic Response http 響應

HTTPResponse 類

大多數情況下,我們的web 應用返回的都是HTTPResponse類的例項,這包括純文字(Plain Text)、HTML、JSON、檔案(File)、重定向(Redirect)、生資料(Raw)。它們的不同,往往體現在這個類的初始化引數content_type上面。

下面是HTTPResponse類的初始化宣告:

class HTTPResponse(BaseHTTPResponse):
    __slots__ = ("body", "status", "content_type", "headers", "_cookies")

    def __init__(
        self,
        body=None,
        status=200,
        headers=None,
        content_type="text/plain",
        body_bytes=b"",
    ):
        self.content_type = content_type

        if body is not None:
            self.body = self._encode_body(body)
        else:
            self.body = body_bytes

        self.status = status
        self.headers = CIMultiDict(headers or {})
        self._cookies = None

子模組response的對應的響應函式最終都會返回一個該類的例項物件。通過給該類的初始化方法傳遞不同的引數值達到生成不同型別的響應的目的。

HTTPResponse類有個主要方法output()用來生成最終的bytes字串返回給瀏覽器(客戶端)。我們不需要理解它的具體實現,只需要知道有它的存在就可以了。除非我們想繼承HTTPResponse類實現自己的特殊類。

StreamingHTTPResponse 類

該類是流響應使用的,對應response.stream()函式和response.file_stream()函式。

該類的初始化方法與HTTPResponse類似但又有不同:

class StreamingHTTPResponse(BaseHTTPResponse):
    __slots__ = (
        "protocol",
        "streaming_fn",
        "status",
        "content_type",
        "headers",
        "_cookies",
    )

    def __init__(
        self, streaming_fn, status=200, headers=None, content_type="text/plain"
    ):
        self.content_type = content_type
        self.streaming_fn = streaming_fn
        self.status = status
        self.headers = CIMultiDict(headers or {})
        self._cookies = None

相對於HTTPResponse類它的實現有些複雜。同樣我們不需要詳細瞭解其內部實現,除非我們需要繼承該類實現自己的流響應型別。

總結

子模組sanic.response負責Sanic的HTTP響應,它提供了型別豐富的響應函式:

  • response.text()
  • response.html()
  • response.json()
  • response.raw()
  • response.file() – async
  • response.file_stream() – async
  • response.stream()
  • response.redirect()

這些響應函式返回的是HTTPResponse類(或StreamingHTTPResponse類)的例項。

猿人學banner宣傳圖

我的公眾號:猿人學 Python 上會分享更多心得體會,敬請關注。

***版權申明:若沒有特殊說明,文章皆是猿人學 yuanrenxue.com 原創,沒有猿人學授權,請勿以任何形式轉載。***

相關文章