Sanic Response HTTP 响应

Sanic教程 2019-03-23 21:33:00 阅读(56802) 评论(0)

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.con 原创,没有猿人学授权,请勿以任何形式转载。***

说点什么吧...