falcon api流与有界\u流与获取\u媒体

2024-05-14 00:35:11 发布

您现在位置:Python中文网/ 问答频道 /正文

有人能帮我理解不同方法之间的区别吗:

  1. request.bounded_stream.read()
  2. request.stream.read()
  3. request.get_media()

它们似乎做了同样的事情,但使用stream或bounded_stream提供了一个类似字节的对象

class test_dev(object):
    async def on_post(self, request, response):
        obj = await request.bounded_stream.read()
        print(obj)

class test_dev(object):
    async def on_post(self, request, response):
        obj = await request.stream.read()
        print(obj)

class test_dev(object):
    async def on_post(self, request, response):
        obj = await request.get_media()
        print(obj)

Tags: devtestselfobjreadstreamasyncobject
1条回答
网友
1楼 · 发布于 2024-05-14 00:35:11

streambounded_stream是类似文件的包装器,用于访问来自服务器的请求正文数据流。这些是不可入座的,据我所知,也不可能偷看它们

它们之间的区别在于后者绑定到请求的content_length,其中stream的行为可能因系统而异。这在official documentation中有详细说明

至于get_media(),它是media属性的包装器。从documentation中,您可以阅读:

Warning:

This operation will consume the request stream the first time it’s called and cache the results. Follow-up calls will just retrieve a cached version of the object.

所以,当您第一次访问request.media时,请求流被消耗和缓存,这意味着从那一刻起streambounded_stream将返回并清空数据流。默认情况下,应用程序将假定内容类型为application/json,并使用json库对内容进行序列化和反序列化

文档中不太清楚的是,如果您选择访问并因此使用streambounded_stream,那么访问media将返回一个错误。 如果您选择自己访问streambounded_stream,您还必须自己存储数据

相关问题 更多 >