【问题标题】:How to embed images to pandas DataFrame and show in flask webpage如何将图像嵌入到 pandas DataFrame 并在烧瓶网页中显示
【发布时间】:2017-12-16 12:14:52
【问题描述】:

我想向 Flask 页面显示一个包含一列图像和其余列是文本的表格。我可以在 jupyter notebook 中显示带有图像的表格。但我无法导出为可以嵌入到烧瓶中以显示图像的 html 代码。相反,我看到的只是文字<img src="http://url.to.image.png"/>

    import pandas as pd
    from IPython.display import Image, HTML
    df['IMAGE'] = df['IMGLINK'].apply(lambda x: '<img src="{}"/>'.format(x) if x else '')
    pd.set_option('display.max_colwidth', -1)
    HTML(df.to_html(escape=False))

在我的 Flask app.py 代码中,我有以下内容:

    @app.route('/result', methods=['POST'])
    def result():
        pd.set_option('display.max_colwidth',-1)
        df = pd.read_csv('DATA_1.csv')
        df['IMAGE'] = df['IMGLINK'].apply(lambda x: '<img src="{}"/>'.format(x) if x else '')
        df_html = dfresult.to_html(index=False)#line_width=60, col_space=70
        return render_template('result.html', datatable=df_html)

在我的 result.html 中,我有一行 {{ datatable | safe }}

【问题讨论】:

  • 为什么需要为此使用 pandas?
  • 因为我将数据存储在 pandas 中,并且 df.to_html() 提供了我需要的大部分内容,除了在烧瓶 html 中显示图像。

标签: python html image pandas flask


【解决方案1】:

图像未呈现,因为标记被编码为文本,而不是 html 如果你想从数据帧中渲染图像,你需要使用 Markup().unescape() 方法。

html = Markup(dataframeName.to_html(classes='data')).unescape() 

这会将 &lt 转换为

如果你想知道为什么会这样,你可以在 chrome 中按 F12,选择标签并右键单击 > 编辑为 html,你会看到你的图像标签看起来像这样: &amp;lt;img src='url_path'&amp;gt; 但是,它应该看起来像:&lt;img src='url_path'&gt;

【讨论】:

    猜你喜欢
    • 2020-09-14
    • 1970-01-01
    • 2021-06-28
    • 1970-01-01
    • 2021-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多