Micropython Webserver:提供大的文本文件,没有内存分配失败



我的项目包括一个使用ESP32的web服务器andmicropython v1.12

背景:

我想创建配置页面,允许我输入WiFi凭据连接我的ESP到我的家庭网络。我在开始时运行一个在ESP32上运行的web服务器。为此,我计划使用Bootstrap和他们的CSS样式表。

基本上我在启动服务器使用:

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

如果客户端连接到我的web服务器,我正在解析URL并调用handle-方法。我的css-files也是如此。

# Get the URL
url = ure.search("(?:GET|POST) /(.*?)(?:\?.*?)? HTTP", request).group(1).decode("utf-8").rstrip("/")
# Math the url
if url == "":
handle_root(client)
elif url == "bootstrap.min.css":
handle_css(client, request, path='bootstrap.min.css')
else:
handle_not_found(client, url)

我使用以下代码行进行响应:

def handle_css(client, request, path):
wlan_sta.active(True)
path = './config_page/' + path # The path to the css
f = open(path, 'r') # Open the file
client.send(f.read()) # Read the file and send it
client.close()
f.close()

文件bootstrap.min.css大约有141kB。我正在耗尽内存读取这个文件并使用套接字发送它:

MemoryError: memory allocation failed, allocating 84992 bytes

有没有一种方法来服务"大"像.css文件?配置页面依赖于其中一些文件。

当然。这里的问题可能是这一行client.send(f.read()),它读取整个文件到内存并将其发送到客户端。与其一次读取整个文件,不如尝试以1KB的块读取并将其发送到客户端。

f = open(path, 'r') # Open the file
while True:
chunk = f.read(1024) # Read the next 1KB chunk
if not chunk:
break
client.send(chunk) # Send the next 1KB chunk
client.close()
f.close()

最新更新