【问题标题】:Correct way to send data from the back-end to the front-end with webbapp2?使用 webbapp2 将数据从后端发送到前端的正确方法?
【发布时间】:2018-05-12 10:46:15
【问题描述】:

我正在学习,但我被一些我无法理解的东西所困扰。

我有一个使用 python GAE 和 webbapp2 构建的简单的 hello world 应用程序。

我想使用 D3.js 在前端显示图表

如果我能够将一些数据直接显示到我的前端 (<p>{{data}}</p>) 的 HTML 部分中,我将无法在我的前端的 <script> </script> 标记中传递任何数据。

这是我后端的MainHandler

MainHandler(webapp2.RequestHandler):
    def get(self):
        data = [{'Letter': 'A', 'Freq': 20  },{'Letter' : 'B','Freq': 12},{'Letter' : 'C','Freq': 47}]
        template_values = {
            'data' : data
        }
        path = os.path.join(os.path.dirname(__file__), 'index.html')
        self.response.out.write(template.render(path, template_values))

app = webapp2.WSGIApplication([
    ('/', MainHandler),
], debug=True)

在前端我有一个简单的console.log({{data}}) 导致以下错误Unexpected token &

我想这里有一些我不明白的地方,但我不知道是什么。

【问题讨论】:

    标签: python webapp2


    【解决方案1】:

    模板引擎是escaping您的数据,以防止它混淆浏览器的渲染引擎,或导致安全问题。所以

    [{'Letter': 'A', 'Freq': 20 }]

    呈现为

    [{'Letter': 'A', 'Freq': 20}]

    [{&#quot;Letter&#quot;: &#quot;A&#quot;, &#quot;Freq&#quot;: 20}]

    这是混淆console.log,这是一个不知道html转义的javascript函数。

    您可以在 Jinja2 中使用 safe 过滤器覆盖此行为。

    console.log({{ data|safe }})

    请注意,您应该只覆盖对受信任数据的转义。

    【讨论】:

      猜你喜欢
      • 2021-05-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-28
      相关资源
      最近更新 更多