python response的数据类型_Python Web框架Sanic Response HTTP 响应

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

类)的实例。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值