file - Micropython Webserver:提供大型文本文件而不会出现内存分配失败
问题描述
我的项目包括一个使用ESP32和micropython v1.12的网络服务器
背景:
我想创建允许我输入 WiFi 凭据以将我的 ESP 连接到我的家庭网络的配置页面。我这样做是在启动时运行在我的 ESP32 上运行的网络服务器。为此,我计划使用 Bootstrap 和他们的 CSS 样式表。
基本上我正在使用以下方式启动服务器:
server_socket = socket.socket()
server_socket.bind(addr)
server_socket.listen(1)
...
如果客户端连接到我的网络服务器,我将解析 URL 并调用handle
-method。我的css文件也是如此。
# 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()
推荐阅读
- reactjs - 无法使用 create-react-app 创建新的反应项目
- shell - 如何直接从脚本向 ftp 终端提供输入
- clickhouse - 了解 clickhouse 分区
- r - Shiny:如何识别正在选择哪个 SelectInput() 并在 server.r 中使用该信息
- r - ggplot2:从列表和常见图例中在多个页面上绘制图形
- scala - 将 DataFrame 写为按列分区的 CSV 时如何保留它的顺序?
- python - 如何将 asyncio create_connection 用于 IPv6 地址?
- java - 未处理的异常类型 Throwable without generic type
- java - 从字符串中提取占位符
- arrays - 如何并行运行 API 调用 (Node.js)