【问题标题】:Quart/Flask render_template return compact jsonQuart/Flask render_template 返回紧凑的 json
【发布时间】:2021-10-15 21:28:59
【问题描述】:

我正在使用 Quart(本质上是 Flask for HTTP/2)来提供一些 JSON 内容。 JSON 内容以漂亮的打印格式驻留在 templates/ 目录中,例如

example.json

{
  "key1": "value1",
  "list1": [
    {
      "key2": "{{ keyword_arg2 or "value2"}}",
      "list2": [
        {
          "key3": "value3 with spaces",
          "key4": "value4"
        }
      ]
    }
  ]
}

如果我只是return render_template('example.json'),它将保留原始文件中的所有空白。我想返回一个紧凑的形式,即

{"key1":"value1","list1":[{"key2":"value2","list2":[{"key3":"value3 with spaces","key4":"value4"}]}]}

有没有一种好方法可以做到这一点(理想情况下,也可以将内容类型设置为 application/json)。到目前为止,我想出的是:

body = await render_template('example.json')
body = body.replace('\n', '')
body = ''.join(body.split())
r = await make_response(body)
r.headers.set('Content-type', 'application/json')
return r

但是它不能很好地处理值中的空格(这个版本完全删除了它们)。 Quart中的jsonify函数自动将Content-type设置为application/json,但是对render_template返回的字符串似乎并没有很好的操作,除非我用错了。

【问题讨论】:

    标签: python templates flask render quart


    【解决方案1】:

    render_template 将返回一个字符串,然后您可以将其解析为 JSON 并从路由返回。然后,这将使用应用程序的 JSON 配置值返回 JSON 响应,the defaults are linked here 例如

    import json
    
    @app.get("/")
    async def route():
        body = await render_template('example.json')
        data = json.loads(body)
        return data
    

    请注意,从 Quart 路由返回字典等同于调用 jsonify 并返回该结果。

    【讨论】:

    • 这是完美的。谢谢!
    猜你喜欢
    • 2018-09-12
    • 2021-09-26
    • 1970-01-01
    • 1970-01-01
    • 2017-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-14
    相关资源
    最近更新 更多