Serve string containing HTML as webpage

Question:

This code serves a webpage (using micropython on a microcontroller). I don’t think the use of microdot.py (a Flask-like library) is important for the question, but I apologize this it not reproducible without that and a microcontroller connected to a wi-fi network.

from microdot import Microdot

myhtml =    """
            <!DOCTYPE html>
            <html>
            <p>LED is {state}</p>
            </body>
            </html>
            """
    
app = Microdot()

@app.route('/')
def index(request):
    state = 'OFF'
    return str(  myhtml.format(state=state)  ) 

if __name__ == '__main__':
    app.run(debug=True)

The browser interprets what it gets as text rather than HTML so on the browser it looks like the below instead of displaying "LED is OFF" without the HTML tags.

       <!DOCTYPE html>
       <html>
       <p>LED is OFF</p>
       </body>
       </html>

I imagine a simple adjustment to my string formatting commands should fix this? Omitting the str call doesn’t help.

Asked By: Alex Holcombe

||

Answers:

According to documentation Responces

example A Simple Microdot Web Server

method index must to return next format

return myhtml.format(state=state), {'Content-Type': 'text/html'}
Answered By: Ronin
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.