【问题标题】:Micropython Webserver: Serve large textfiles without memory allocation failureMicropython Web Server:服务大型文本文件而不会出现内存分配失败
【发布时间】:2021-05-13 02:58:04
【问题描述】:

我的项目包括一个使用 ESP32micropython v1.12

的网络服务器

背景:

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

基本上我正在使用以下方式启动服务器:

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

如果客户端连接到我的网络服务器,我将解析 URL 并调用handle-方法。我的 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 文件这样的“大”文件?配置页面依赖于这些文件。

【问题讨论】:

    标签: file websocket esp32 micropython


    【解决方案1】:

    当然。这里的问题可能是这行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()
    

    【讨论】:

      猜你喜欢
      • 2022-01-22
      • 2021-05-23
      • 1970-01-01
      • 1970-01-01
      • 2022-11-11
      • 1970-01-01
      • 2012-03-26
      • 1970-01-01
      相关资源
      最近更新 更多