You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在MicroPython热点模式Web服务器中传递HTML输入到Python变量

在MicroPython(ESP8266)AP模式下获取HTML表单POST数据的轻量方案

你可以通过解析HTTP请求的方法与请求体来提取表单数据,无需依赖任何重型框架,完全基于MicroPython自带的模块实现。以下是修改后的完整代码及关键步骤说明:

核心思路

  1. 区分HTTP请求的GET与POST方法:GET用于返回登录页面,POST用于处理表单提交
  2. 提取POST请求的请求体内容,解析表单的URL编码键值对
  3. 将解析后的表单值存入Python变量,完成后续逻辑(验证、存储等)

修改后的完整代码

import network
import socket
from urllib.parse import parse_qs

# 配置AP热点(请替换为你的热点名称和密码)
ap_ssid = "ESP8266-AP"
ap_psw = "12345678"

ap = network.WLAN(network.AP_IF)    
ap.active(True)                     
ap.config(essid=ap_ssid, password=ap_psw) 

s = socket.socket() 
s.bind(('', 80))  
s.listen(5)


def login_page(): 
  html = """
  <html>
    <head>
      <meta name="viewport" content="width=device-width, initial-scale=1", charset="UTF-8">
      <title>Login Form</title>
      <style>
        .center { margin: 50px auto; width: 300px; padding: 20px; border: 1px solid #ccc; border-radius: 8px; }
        .header { font-size: 20px; font-weight: bold; margin-bottom: 20px; text-align: center; }
        input { width: 100%; padding: 10px; margin: 8px 0; box-sizing: border-box; }
        input[type="submit"] { background-color: #4CAF50; color: white; border: none; cursor: pointer; }
      </style>
    </head>
    <body>
      <div class="center">
         <div class="header">
            Login Form
         </div>
         <form method="post">
            <input type="text" placeholder="Username" id="wifi_ssid" name="wifi_ssid" required>
            <input id="wifi_psw" name="wifi_psw" type="password" placeholder="Password" required>
            <input type="submit" value="Sign in">
         </form>
      </div>
    </body>
  </html>"""
  return html

def success_page(ssid):
  html = f"""
  <html>
    <head>
      <meta name="viewport" content="width=device-width, initial-scale=1", charset="UTF-8">
      <title>Success</title>
    </head>
    <body>
      <div style="text-align: center; margin-top: 100px;">
        <h2>登录成功!</h2>
        <p>你输入的用户名:{ssid}</p>
        <p>密码已接收(出于安全未显示)</p>
        <a href="/">返回登录页</a>
      </div>
    </body>
  </html>"""
  return html

while True:
  conn, addr = s.accept()
  try:
    request = conn.recv(1024).decode('utf-8')
    # 解析请求方法
    method = request.split(' ')[0]
    
    if method == 'POST':
      # 提取POST请求体(从空行之后的内容)
      body_start = request.find('\r\n\r\n') + 4
      form_data_str = request[body_start:]
      # 解析表单数据为字典
      form_data = parse_qs(form_data_str)
      
      # 提取表单值,处理可能的空值情况
      wifi_ssid = form_data.get('wifi_ssid', [''])[0]
      wifi_psw = form_data.get('wifi_psw', [''])[0]
      
      # 这里可以添加验证、存储等逻辑,比如打印到串口
      print(f"Received SSID: {wifi_ssid}, Password: {wifi_psw}")
      
      # 返回成功页面
      response = success_page(wifi_ssid)
    else:
      # GET请求返回登录页面
      response = login_page()
    
    # 发送HTTP响应头与内容
    conn.send('HTTP/1.1 200 OK\r\n')
    conn.send('Content-Type: text/html\r\n')
    conn.send('Connection: close\r\n\r\n')
    conn.send(response)
  except Exception as e:
    print(f"Error handling request: {e}")
  finally:
    conn.close()

关键代码说明

  • urllib.parse.parse_qs:MicroPython自带的轻量解析工具,能直接将URL编码的表单数据转为字典,资源占用极低,完全适配ESP8266的硬件限制
  • 请求解析:通过拆分请求字符串获取请求方法,POST请求的表单数据位于HTTP头部之后的空行(\r\n\r\n)之后,提取后即可解析
  • 值提取:parse_qs返回的字典中每个键对应的值是列表(支持同键多值),所以用[0]取第一个元素即可
  • 异常处理:添加try-finally确保连接始终关闭,避免资源泄漏

内容的提问来源于stack exchange,提问作者Giorgio

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 23:50:28