首页 > 编程语言 >How can I fix that my variable goes into the formatted string of my html code in python

How can I fix that my variable goes into the formatted string of my html code in python

时间:2024-12-01 10:34:03浏览次数:7  
标签:code string temp my html print sensor response temperature

题意:我该如何修复我的变量正确地插入到 Python 中 HTML 代码的格式化字符串中?

问题背景:

For a project I'm running a raspberry pi Pico wh based webserver that should get the inputs of the temperature sensor and display it on the website. I am however not very informed about javascript and html. Because my code already looks bad I've removed the css elements. The reason it has to be like this is because the main program needs to run in micropython on my pi.

在一个项目中,我运行了一个基于 Raspberry Pi Pico W 的 Web 服务器,用于获取温度传感器的输入并在网站上显示。然而,我对 JavaScript 和 HTML 并不是很了解。因为我的代码已经显得很乱,所以我移除了 CSS 元素。之所以必须这样做,是因为主程序需要在我的 Pico 上以 MicroPython 的形式运行。

Note: It is however important the sensor and the raspberry keep being the only physical components.

注意:然而,传感器和 Raspberry Pi 必须始终是唯一的物理组件。

I'm hoping someone can give a solution or guidance, maybe even a diffrent aproach.

我希望有人能提供解决方案或指导,甚至是一个不同的实现方法。

Here is my code:        这是我的代码:

#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')


Ive tried making the entire html block a formatted string(python), so I can adjust the value but it doesnt work.

我尝试将整个 HTML 块做成一个格式化字符串(Python),以便调整值,但没有成功。

Ive done a few days of research but I'm not much further.

我已经做了几天的研究,但进展不大。

问题解决:

Let's distill the relevant parts of this question.

让我们提炼出这个问题的相关部分。

You have a script that functionally does the following.

你有一个脚本,功能上实现了以下操作。

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

#> The current temperature is {sensor_temp}.

That is, you acquire a sensor_temp from somewhere, stick it into a string, and later serve (or here, print) that string. The HTML, javascript, and raspberry pi are all red herrings — this is really a question about string formatting.

也就是说,你从某个地方获取一个 `sensor_temp`,将其插入到一个字符串中,然后稍后提供(或者在这里是打印)该字符串。HTML、JavaScript 和 Raspberry Pi 都是误导因素——这实际上是一个关于字符串格式化的问题。

The easiest thing to do is to preface the string by f and use fstrings.

最简单的方法是在字符串前加上 `f`,使用 f-strings。

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.

Or you could use old format strings, e.g.

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

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.

Or you could manually create the string.

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

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

#> The current temperature is 10.

If this is a broad type of project that you're going to do, it might be worth looking into using the jinja templating engine. This is a small library that plays very well with python.

如果这是一个你将要进行的广泛类型的项目,值得考虑使用 `jinja` 模板引擎。这是一个与 Python 配合得非常好的小型库。

标签:code,string,temp,my,html,print,sensor,response,temperature
From: https://blog.csdn.net/suiusoar/article/details/144165797

相关文章

  • Type definition error: [array type, component type: [simple type, class java.lan
     详细报错信息:Typedefinitionerror:[arraytype,componenttype:[simpletype,classjava.lang.String]];nestedexceptioniscom.fasterxml.jackson.databind.exc.InvalidDefinitionException:Cannotconstructinstanceof`java.lang.String[]`:noString-argu......
  • AtCoder Beginner Contest 382 Solution
    A-DailyCookie(abc382A)题目大意给定一个长度为N的字符串,有很多.和@,一共有D天,每天会使一个@变成.,问D天之后有几个.解题思路数一下有几个.,答案会加D个.。代码voidsolve(){intn,d;strings;cin>>n>>d>>s;cout<<count(s.begin(),s.end(),'.......
  • AtCoder Beginner Contest 380 Solution
    A-1232336个数问是不是1个1,2个2,3个3#include<bits/stdc++.h>usingnamespacestd;inta[4];intmain(){strings;cin>>s;for(inti=0;i<s.size();i++)a[s[i]-'0']++;if(a[1]==1&&a[2]==2......
  • MySQL事务学习-2024-11-30
    [学习记录]MySQL事务锁的兼容情况总结-GPTS锁和X锁的兼容性在MySQL中,S锁(共享锁)和X锁(排他锁)的兼容性如下:锁类型S锁X锁S锁√兼容×不兼容X锁×不兼容×不兼容具体说明:S锁(共享锁):多个事务可以同时对同一数据加S锁(即允许多个事务同时读取数据)。如果一个事务已经持有......
  • AtCoder Beginner Contest 382 赛后复盘
    abc381的赛后总结不见了。(人话:没写)A-B模拟即可C因为好吃的会被前面的人吃掉,后面的人只能捡垃圾吃,所以实际上能吃东西的\(a\)成单调递减。所以我们直接二分在哪个区间即可,时间复杂度\(O(m\logn)\)。点击查看代码#include<bits/stdc++.h>#definelllonglong#de......
  • AtCoder Beginner Contest 382
    A-DailyCookie题意给定长为\(n\)的串,“.”代表空,“@”代表饼干,一天吃一块饼干,问\(d\)天后有几个格子是空的。思路模拟。代码点击查看代码#include<bits/stdc++.h>usingnamespacestd;#defineintlonglongtypedefpair<int,int>pii;constintmxn=1e......
  • 【Leecode】Leecode刷题之路第66天之加一
    题目出处66-加一-题目出处题目描述个人解法思路:todo代码示例:(Java)todo复杂度分析todo官方解法66-加一-官方解法方法1:找出最长的后缀9思路:代码示例:(Java)publicclassSolution1{publicint[]plusOne(int[]digits){intn=di......
  • 【Leecode】Leecode刷题之路第65天之有效数字
    题目出处65-有效数字-题目出处题目描述个人解法思路:todo代码示例:(Java)todo复杂度分析todo官方解法65-有效数字-官方解法方法1:确定有效状态自动机思路:代码示例:(Java)publicclassSolution1{publicbooleanisNumber(Strings){......
  • 【Leecode】Leecode刷题之路第64天之最小路径和
    题目出处64-最小路径和题目描述个人解法思路:todo代码示例:(Java)todo复杂度分析todo官方解法64-最小路径和-官方解法方法1:动态规划思路:代码示例:(Java)publicclassSolution1{publicintminPathSum(int[][]grid){if(grid==......
  • 0day圣乔E*P系统NamedParameterSingleRowQueryConvertor.queryForString.dwr存在SQL注
         0x01产品概述    圣乔E*P系统NamedParameterSingleRowQueryConvertor.queryForString.dwr存在SQL注入漏洞 通用描述管理和发布于一体的智能化平台,广泛应用于新闻、媒体和各类内容创作机构。该平台支持多终端、多渠道的内容分发,具备素材管理、编辑加工、智......