Sanic 生成 HTTP 响应的子模块是
sanic.response
。该模块可以生成多种格式的HTTP响应,包括纯文本(Plain Text)、HTML、JSON、文件(File)、数据流(Streaming)、文件流(File Streaming)、重定向(Redirect)、生数据(Raw)。分别对应该子模块的响应函数:
response.text()
response.html()
response.json()
response.raw()
response.file()
– async
response.file_stream()
– async
response.stream()
response.redirect()
所有返回的响应都是一个
HTTPResponse
类(或
StreamingHTTPResponse
类)的实例。这两个类都派生自
BaseHTTPResponse
类。
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
类)的实例。