How to embed images to pandas DataFrame and show in flask webpage

Viewed 1177

I want to show a table with a column of images and rest columns are text, to Flask pages. I can display table with images in jupyter notebook. But I cannot export as html code that can be embedded to flask to show the images. Instead, I saw just text <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))

In my Flask app.py code, I have the following:

    @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)

In my result.html, I have line {{ datatable | safe }}.

1 Answers

Image is not rendering, because the markup is encoded as text, not as html If you looking to render image from dataframe, you need to use Markup().unescape() method.

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

This will convert &lt to < and likewise other symbols to tags.

If you want to see, why this is happening, you can F12 in chrome, select tag and right click > edit as html, you will see that your image tag is looking something like: &lt;img src='url_path'&gt; however, it should look like: <img src='url_path'>

Related