【问题标题】:pyramid FileResponse encoding金字塔文件响应编码
【发布时间】:2013-09-17 01:33:30
【问题描述】:

我正在尝试提供 base64 编码的图像文件,但失败了。要么我得到 UTF-8 编码的响应,要么以一种有趣的方式得到 return response 行错误。大多数我尝试过的所有东西都可以看作是下面摘录中的注释代码。回溯的详细信息如下。

我的问题是:如何返回 base64 编码文件?

        #import base64
        #with open(sPath, "rb") as image_file:
            #encoded_string = base64.b64encode(image_file.read())
        dContentTypes = {
        'bmp'   : 'image/bmp',
        'cod'   : 'image/cis-cod',
        'git'   : 'image/gif',
        'ief'   : 'image/ief',
        'jpe'   : 'image/jpeg',
        .....
        }
        sContentType = dContentTypes[sExt]
        response = FileResponse(
                            sPath,
                            request=request,
                            content_type= sContentType#+';base64',
                            #content_encoding = 'base_64'
                            #content_encoding = encoded_string
                            )
        return response

取消注释 #content_encoding = encoded_string 行会给我错误:

 AssertionError: Header value b'/9j/4AAQSkZJRgABAQAA' is not a string in ('Content-Encoding', b'/9j/4AAQSkZJRgABAQAA....')

【问题讨论】:

  • 为什么不直接提供图片?只有在 CSS 或 HTML 中直接嵌入时才需要 Base64 编码资源。提供 HTTP 响应时,您只需提供未编码的资源。
  • @MartijnPieters:这是野兽的本性......我有一个脚本可以抓取图像并将它们存储在一个不错的地方,我有一个需要显示它们的页面。不幸的是,由于我无权访问配置,我无法以正常方式为他们提供服务。此外,由于应用程序的性质,我需要能够动态获取其中一些(我可以将它们隐藏在页面上的某个位置并根据需要取消隐藏它们,但它们有很多)

标签: pyramid content-encoding


【解决方案1】:

FileResponse 专门用于上传文件作为响应(因此是路径参数)。在您的情况下,您希望在上传文件之前对其进行 base64 编码。这意味着没有FileResponse

由于您已将文件读入内存,您只需将内容上传到Response

response = Response(encoded_string,
                    request=request,
                    content_type=sContentType+';base64')

我实际上不确定content_encoding 与类型上的;base64 相比如何,但我认为编码更常用于压缩内容。 YMMV。

【讨论】:

    【解决方案2】:

    您看到的错误是告诉您 Content-Type 不是字符串。 Content-Type 是一个 HTTP 标头。据我所知,HTTP 标头必须是字符串。

    我相信您想要作为响应正文传递的 base64 编码文件。 FileResponse 在这里不合适,因为您可能希望将编码字符串作为正文传递,而 FileResponse 需要一个路径,然后它会读取并设置正文。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-02-25
      • 2022-01-19
      • 2018-12-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-09
      • 2020-12-23
      相关资源
      最近更新 更多