How to use utemplate with Microdot?

General discussions and questions abound development of code with MicroPython that is not hardware specific.
Target audience: MicroPython Users.
Post Reply
karnov
Posts: 1
Joined: Tue Feb 01, 2022 11:24 am

How to use utemplate with Microdot?

Post by karnov » Tue Feb 01, 2022 11:40 am

Hello everyone,

I am trying my luck with micropython on ESP32, I got some basic experience with microcontrollers and python but that's about it.
I wanted to run http server on ESP32 and it all went great with Microdot, I got it up and running in minutes.

But I got totally stuck when trying to use utemplate package with it - I was looking for some way to use templates and found a mention that utemplate works nicely with Microdot but I could not figure out a practical way to do it as the utemplate docs page seem to be too abstract for my micropython level (https://github.com/pfalcon/utemplate).

So here is my code that runs just fine on ESP32:

Code: Select all

from microdot import Microdot, Response
import utemplate
import network

app = Microdot()

htmldoc = '''<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Microdot Example Page</title>
        <link rel="stylesheet" href="/styles.css">
    </head>
    <body>
        <div>
            <h1>Microdot Example Page</h1>
            <p>Hello from Microdot!</p>
            <p><a href="/shutdown">Click to shutdown the server</a></p>
        </div>
    </body>
</html>
'''

@app.route('/')
def home(request):
    return Response(body=htmldoc, headers={'Content-Type': 'text/html'})

@app.route('/styles.css')
def styles(request):
    
    file = open("styles.css", "r")
    body = file.read()
    file.close()
    
    return Response(body=body, headers={'Content-Type': 'text/css'})

def connect():
    
    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)
    
    if not wlan.isconnected():
        print('Connecting to network...')
        wlan.connect('***', '***')
        while not wlan.isconnected():
            pass
    
    print('Network config:', wlan.ifconfig())
    
    
connect()

app.run(debug=True)
I can successfully install all components (Microdot, utemplate) to my ESP32 using Thonny's package manager (when I tried to do it from ESP32 it was complaining about memory shortage).

So can someone give me an example for rendering a view in def home(request) if I moved the
htmldoc to a home.tpl file? Or maybe a tip what other engine I could use?

Any help much appreciated.
Karnov

Post Reply