如何修复我的变量在Python中进入HTML代码的格式化字符串?

1 投票
1 回答
37 浏览
提问于 2025-04-14 16:49

我正在做一个项目,使用树莓派 Pico 作为网络服务器,目的是获取温度传感器的数据并在网站上显示。不过,我对 JavaScript 和 HTML 不是很了解。

因为我的代码看起来已经很糟糕,所以我把 CSS 部分去掉了。

这样做的原因是因为主要程序需要在我的树莓派上用 MicroPython 运行。

注意:传感器和树莓派必须是唯一的物理组件。

我希望有人能给我一些解决方案或指导,甚至是不同的方法。

这是我的代码:

#import libraries
from machine import Pin, I2C
import time
import mcp9808
import ssd1306
import network
import socket

#initialize temp sensor
i2c = I2C(1,scl=Pin(3), sda=Pin(2), freq=10000)
mcp = mcp9808.MCP9808(i2c)

#initialize display
i2c = I2C(0, sda=Pin(20), scl=Pin(21))
display = ssd1306.SSD1306_I2C(128, 64, i2c)

#initialize onboard led
led = machine.Pin("LED", machine.Pin.OUT)
led.on()


ssid = 'SSID'
password = 'WIFI_PASSWORD'

wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(ssid, password)

while True:
    # get the temperature (float)
    SensTemp = mcp.get_temp()
    SensTemp = "{:.2f}".format(SensTemp)

    #display.poweron()
    display.fill(0)
    display.text(SensTemp, 0, 0, 1)
    display.text("C", 42, 0, 1)
    display.show()



    html = """<!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Temperature Display</title>
    </head>
    <body>

    <h1>Current Temperature:</h1>
    <p id="temperature"></p>

    <script>
    // Simulated temperature value
    var temperatureValue = {SensTemp}; // You can replace this with actual temperature data

    // Update the temperature display
    function updateTemperature() {
      var temperatureElement = document.getElementById("temperature");
      temperatureElement.textContent = temperatureValue + "°C";
    }

    // Call the function to initially display the temperature
    updateTemperature();
    </script>

    </body>
    </html>
    """


    # Wait for connect or fail
    max_wait = 10
    while max_wait > 0:
        if wlan.status() < 0 or wlan.status() >= 3:
            break
        max_wait -= 1
        print('waiting for connection...')
        time.sleep(1)

    # Handle connection error
    if wlan.status() != 3:
        raise RuntimeError('network connection failed')
    else:
        print('connected')
        status = wlan.ifconfig()
        print( 'ip = ' + status[0] )

    # Open socket
    addr = socket.getaddrinfo('0.0.0.0', 80)[0][-1]

    s = socket.socket()
    s.bind(addr)
    s.listen(1)

    print('listening on', addr)

    # Listen for connections
    while True:
        try:
            cl, addr = s.accept()
            print('client connected from', addr)
            cl_file = cl.makefile('rwb', 0)
            while True:
                line = cl_file.readline()
                if not line or line == b'\r\n':
                    break
            response = html
            cl.send('HTTP/1.0 200 OK\r\nContent-type: text/html\r\n\r\n')
            cl.send(response)
            cl.close()

        except OSError as e:
            cl.close()
            print('connection closed')


我试过把整个 HTML 块做成一个格式化字符串(在 Python 中),这样我就可以调整数值,但没有成功。

我研究了几天,但进展不大。

1 个回答

1

我们来简单梳理一下这个问题的重点。

你有一个脚本,基本上是做以下事情。

sensor_temp = 10
html = """
The current temperature is {sensor_temp}.
"""
response = html
print(response)

#> The current temperature is {sensor_temp}.

也就是说,你从某个地方获取一个 sensor_temp,把它放进一个字符串里,然后再显示(或者说打印)这个字符串。这里提到的HTML、JavaScript和树莓派其实并不重要,真正的问题是关于字符串格式化的。

最简单的方法是把字符串前面加上 f,然后使用 fstrings

sensor_temp = 10
# Note the f on the following line, the only change.
html = f"""   
The current temperature is {sensor_temp}.
"""
response = html
print(response)

#> The current temperature is 10.

或者你也可以使用旧的格式字符串,比如:

sensor_temp = 10
# Now no f, and no labelled input in braces {} below.
html = """   
The current temperature is {}.
"""
response = html.format(sensor_temp)
print(response)

#> The current temperature is 10.

又或者你可以手动创建这个字符串。

sensor_temp = 10
html = "The current temperature is " + str(sensor_temp) +".\n" 
response = html
print(response)

#> The current temperature is 10.

如果这是一个比较大的项目,值得考虑使用 jinja 模板引擎。这是一个与Python配合得非常好的小库。

撰写回答