[Django]-In Python, how to open a string representing HTML in the browser?

4👍

Use Data URL:

import base64

html = b"..."

url = "text/html;base64," + base64.b64encode(html)
webbrowser.open(url)
👤Marat

0👍

you could convert the html string to url:

https://docs.python.org/2/howto/urllib2.html

0👍

Following Launch HTML code in browser (that is generated by BeautifulSoup) straight from Python, I wrote a test case in which I write the HTML to a temporary file and use the file:// prefix to turn that into a url accepted by webbrowser.open():

import tempfile
import webbrowser
from django.test import SimpleTestCase
from django.template.loader import render_to_string


class ViewEmailTemplate(SimpleTestCase):
    def test_view_email_template(self):
        html = render_to_string('ebay/activate_to_family.html')
        fh, path = tempfile.mkstemp(suffix='.html')
        url = 'file://' + path

        with open(path, 'w') as fp:
            fp.write(html)
        webbrowser.open(url)

(Unfortunately, I found that the page does not contain images referenced by Django’s static tag, but that’s a separate issue).

0👍

Here’s a more concise solution which gets around the possible ValueError: startfile: filepath too long for Windows error in the solution by @marat:

from pathlib import Path

Path("temp.html").write_text(html, encoding='utf-8')
webbrowser.open("temp.html")
Path("temp.html").unlink()

Leave a comment