【问题标题】:Render html response from string in python tornado library从 python tornado 库中的字符串渲染 html 响应
【发布时间】:2022-01-17 15:24:36
【问题描述】:

我需要像这样在龙卷风中呈现来自 html 字符串的响应:

self.method_to_render_html_from_string('<h1>Hello</h1>')

我该怎么做?龙卷风版本是 6.1。 现在它的显示方式如下: enter image description here

与龙卷风无关的答案也很受欢迎:)

【问题讨论】:

    标签: python html tornado


    【解决方案1】:

    如果您想发送回复,请使用self.write

    def get(self):
        self.write('<h1>Hello</h1>')
    

    如果你想从模板字符串生成html,那么使用tornado.template.Template:

    from tornado.template import Template
    
    def get(string):
        t = Template('<h1>Hello {{ name }}</h1>')
        self.write(t.generate(name='John'))
    

    更新:

    如果响应以纯文本形式发送,您可以尝试设置 Content-Type: text/html 标头以将响应以 HTML 格式发送:

    def get(self):
        self.set_header('Content-Type', 'text/html')
        self.write('<h1>Hello</h1>)
    

    【讨论】:

    • 如果使用self.write('&lt;h1&gt;Hello&lt;/h1&gt;'),它会显示在带有&lt;h1&gt;标签的浏览器中。可能是什么问题?提前致谢。
    • @RomanIvanets 似乎响应以text/plain 发送,但这很奇怪,因为 Tornado 默认以text/html 发送响应。但是,您尝试设置 Content-Type: text/html 标头。我已经更新了答案。
    • 非常感谢,现在可以使用了 :)
    • 由于缺乏声誉而无法投票。
    • @RomanIvanets 没关系。如果此答案解决了您的问题,您可以通过单击左侧的复选图标将其标记为“已接受”。
    猜你喜欢
    • 2017-09-05
    • 2021-01-30
    • 2016-11-30
    • 2017-03-21
    • 2015-05-15
    • 2022-11-18
    • 2011-02-12
    • 2018-08-30
    • 2019-11-26
    相关资源
    最近更新 更多