Contents
Introduction to IPv6 Technology
IPv6 Background
1.1.1 Limitations of IPv4
IPv4 (Internet Protocol Version 4) is the currently widely deployed Internet protocol, which features a 32-bit address length, theoretically providing approximately 4.29 billion addresses with around 3.647 billion actually available. With the rapid development of the Internet, all IPv4 addresses were fully allocated back in 2019, and the problem of address resource exhaustion has become increasingly severe. As a populous country, China faces a particularly prominent shortage of IPv4 addresses; as of December 2020, China owned 389 million IPv4 addresses, with an average of 3.7 people sharing one address, far below the global average.

1.1.2 Limitations of Transition Technologies
To alleviate the shortage of IPv4 addresses, the industry has adopted technologies such as Network Address Translation (NAT) and Classless Inter-Domain Routing (CIDR). However, these transition schemes can only slow down the rate of address exhaustion, cannot fundamentally solve the problem, and the NAT technology has brought about new issues such as difficulties in security traceability and restricted applications.

1.1.3 Birth and Development of IPv6
The Internet Engineering Task Force (IETF) started planning the next-generation protocol for IPv4 in 1990. In 1994, representatives from various fields of IPng (Internet Protocol Next Generation) formally proposed the IPv6 development plan at the IETF meeting held in Toronto. In December 1995, the IETF released RFC 1883 (Internet Protocol v6 Specification), which marked the official introduction of the IPv6 protocol.In December 1998, this specification was updated to RFC 2460, which was later superseded by RFC 8200 in July 2017. On June 6,2012, the Internet Society held the World IPv6 Launch Day, and a number of well-known websites including Google, Facebook, and Yahoo began to permanently support IPv6 access. In 2016, the Internet Assigned Numbers Authority (IANA) put forward a proposal to the IETF, requiring newly formulated international Internet standards to only support IPv6 and no longer be compatible with IPv4.

The Essence of Binary
1.2.1 Address Length and Capacity
The most fundamental change of IPv6 is that it extends the address length from the 32 bits of IPv4 to 128 bits. The 32-bit address space provides 2^32 (about 4.29 billion) addresses, while the 128-bit address space offers 2^128 addresses, amounting to approximately 340 undecillion (3.4×10^38) in total. This magnitude is claimed to be large enough to assign a unique address to every grain of sand on Earth, fundamentally resolving the problem of address resource exhaustion.
1.2.2 Binary Structure
At the binary level, an IPv6 address is a 128-bit long binary sequence. For example, a complete binary IPv6 address can be expressed as:
00100001110110100000000011010011000000000000000000101111001110110000001010101010000000001111111111111110001010001001110001011010
1.2.3 Logical Division
These 128-bit addresses are logically often divided into two parts:
- Network prefix: Typically 64 bits long, used to identify a network.
- Interface Identifier: Typically a 64-bit value used to identify a specific interface on a network. Interface identifiers are often automatically generated based on physical addresses, a scheme known as EUI-64 (64-bit Extended Unique Identifier).
Address Format and Representation
1.3.1 Standard Notation (Colon Hexadecimal Notation)
For ease of writing and reading, a 128-bit binary address is split along 16-bit boundaries into 8 16-bit blocks. Each 16-bit block is converted into a 4-digit hexadecimal number, separated by colons (:). This notation is called "colon hexadecimal notation".
For example, the above binary address is converted into the standard format as follows:
21DA:00D3:0000:2F3B:02AA:00FF:FE28:9C5A

1.3.2 Compression Representation Rules
To simplify notation, several compression rules are defined for IPv6 addresses:
- Omitting leading zeros: Leading zeros in each 16-bit block may be omitted. For example,
00D3can be written asD3, and02AAcan be written as2AA. However, each block must retain at least one digit. - Continuous zero block compression: One or more consecutive 16-bit blocks consisting entirely of zeros can be represented by a double colon (
::), but the double colon can only be used once in a single address. - After applying the compression rule, the above address can be abbreviated as:
21DA:D3:0:2F3B:2AA:FF:FE28:9C5A

1.3.3 Other Notations
- Dotted hexadecimal notation: Remove the colons from 8 groups of 16-bit hexadecimal addresses, group each digit with a dot (
.), which is used forip6.arpasubdomains to record the mapping between IPv6 addresses and domain names. For example,2001:0db8:85a3:08d3:1319:8a2e: 0370:7344can be written as2.0.0.1.0.d.b.8.8.5.a.3.0.8.d.3.1.3.1.9.8.a.2.e.0.3.7.0.7.3.4.4. - Embedded IPv4 address representation: In transition mechanisms, the format of
:: FFFF:followed by an IPv4 address can be used, for example,:: FFFF: 192.0.2.1.
Message Structure
1.4.1 Message Composition
An IPv6 packet consists of three parts:
- IPv6 Basic Header: Fixed at 40 bytes, it contains the basic information for packet forwarding.
- IPv6 extension headers: zero, one or more optional headers designed to implement various extended functions.
- Upper Layer Protocol Data Unit: The carried upper-layer protocol data, such as ICMPv6, TCP or UDP packets.
1.4.2 Basic Header Format
The IPv6 basic header is fixed at 40 bytes and contains 8 fields:
| Field | Length | Description |
|---|---|---|
| Version | 4 bits | Protocol version number; for IPv6, this value is 6. |
| Traffic Class | 8 bits | Similar to the IPv4 TOS field; identifies the class or priority of the datagram and supports QoS (Quality of Service). |
| Flow Label | 20 bits | New field in IPv6. Identifies packets belonging to the same flow, so routers can give special handling to real-time traffic and the like. |
| Payload Length | 16 bits | Indicates the length of the rest of the packet that follows the IPv6 header (extension headers and upper-layer protocol data), in bytes. The maximum value is 65535 bytes. |
| Next Header | 8 bits | Specifies the type of the first extension header that follows the IPv6 header, or the type of the upper-layer protocol (such as TCP/UDP). This is the core field for implementing extension functions. |
| Hop Limit | 8 bits | Similar to the TTL in IPv4. It is decremented by 1 at each router, and the packet is discarded when it reaches 0. |
| Source Address | 128 bits | The IPv6 address of the sender. |
| Destination Address | 128 bits | The IPv6 address of the receiver. |
Compared with IPv4, the IPv6 basic header eliminates fields such as IHL (Internet Header Length), Identifier, Flags, Fragment Offset, Header Checksum, Options and Padding, and only adds the Flow Label field, which greatly simplifies the structure and improves the processing efficiency of routers.
1.4.3 Extension Header
IPv6 implements various optional functions via extension headers in a chained structure. Each extension header also contains a "Next Header" field, which points to the next extension header or the upper-layer protocol. RFCs define multiple types of extension headers, mainly including:
| Header Type | Next Header Value | Description |
|---|---|---|
| Hop-by-Hop Options Header | 0 | Must be read and processed by every hop along the transmission path. Used for jumbo payloads, router alerts, etc. |
| Destination Options Header | 60 | Information processed only by the destination node, mainly used for Mobile IPv6. |
| Routing Header | 43 | Similar to IPv4 loose source routing. The source node can specify a particular path for the packet to take. |
| Fragment Header | 44 | Used to fragment a packet when its length exceeds the path MTU (Note: in IPv6 only the source host can fragment; routers along the path no longer fragment). |
| Authentication Header | 51 | Used by IPsec. Provides data origin authentication, data integrity verification, and anti-replay protection. |
| Encapsulating Security Payload Header | 50 | Used by IPsec. In addition to authentication and integrity protection, it also provides data encryption. |
Key Technical Features and Advantages
1.5.1 Huge Address Space
The 128-bit address length provides nearly unlimited address resources (approximately 3.4×10^38 addresses), which is sufficient to meet the access demands of massive devices in future scenarios such as the Internet of Things, 5G, and the Industrial Internet.
1.5.2 Simplified Header and Efficient Processing
Design features such as a fixed 40-byte base header, the removal of checksums, and the relocation of option functions to extension headers have significantly reduced router processing overhead and improved packet forwarding efficiency.
1.5.3 Built-in Security
IPv6 incorporates IPsec (including Authentication Header (AH) and Encapsulating Security Payload (ESP)) as an integral part of the protocol, enabling inherent security at the network layer and providing end-to-end authentication, integrity and confidentiality.
1.5.4 Enhanced QoS Support
Through the "Traffic Class" and "Flow Label" fields, IPv6 can better identify and handle different types of service flows (such as Real Time Communication), laying a foundation for differentiated services.
1.5.5 Improved Multicast and Anycast
- Multicast: IPv6 has enhanced multicast by adding a "scope" field to multicast addresses, which enables better control over the propagation range of multicast traffic.
- Anycast: IPv6 defines a new "anycast" address type. Packets sent to an anycast address are routed to the "closest" one among the set of nodes identified by that address (usually determined based on routing protocol metrics). This can be used for load balance and redundant services.
1.5.6 Plug and Play Address Auto-Configuration
IPv6 supports Stateless Address Autoconfiguration (SLAAC) and stateful address configuration (e. g., DHCPv6). A host can automatically generate a globally unique IPv6 address by receiving the prefix information advertised by routers, which greatly simplifies network management and is particularly suitable for mobile devices and IoT terminals.
1.5.7 Improved mobility support
The Mobile IPv6 protocol is designed to be more efficient. It solves the triangular routing problem in Mobile IPv4 and allows a mobile node to maintain a continuous connection with its corresponding peer when changing access points.
1.5.8 Improved Segmentation Mechanism
In IPv6, packet fragmentation can only be performed at the source host, and routers along the path no longer fragment packets. If a router encounters a packet that exceeds the MTU of its egress interface, it will discard the packet and send an ICMPv6 "Packet Too Big" message to the source, which will then re-perform appropriate fragmentation. This simplifies the work of routers.
Deployment, Application and Current Status
1.6.1 Global Deployment Progress
Since its global launch in 2012, IPv6 deployment has continued to accelerate. As of April 2022, the percentage of users accessing Google services via IPv6 exceeded 40% for the first time. Governments and enterprises around the world are actively advancing the large-scale deployment of IPv6.
1.6.2 Deployment Status and Policies in China
China regards the large-scale deployment of IPv6 as a key strategy underpinning the building of a strong cyber nation. In November 2017, the General Office of the Communist Party of China Central Committee and the General Office of the State Council issued the Action Plan for Promoting the Large-Scale Deployment of Internet Protocol Version 6 (IPv6), which sets the goal of "forming an independent technology system and industrial ecosystem for the next-generation internet and building the world's largest IPv6 commercial application network within 5 to 10 years". As of September 2025, the number of active IPv6 users in China had reached 865 million, ranking among the top globally;The total IPv6 address resources amount to 71,590 blocks (in /32 prefixes), accounting for 14.61% of the world’s allocated IPv6 addresses and ranking second globally.
1.6.3 Key Application Scenarios
- Mobile Internet and 5G: The high-bandwidth, low-latency and high-reliability features of 5G networks require end-to-end IPv6 networks for support. The massive address space can meet the access demands of a huge number of 5G terminals.
- Internet of Things (IoT): With features such as a massive address space, automatic address configuration, and low-power adaptation (for instance, the 6LoWPAN protocol can compress IPv6 headers to just a few bytes), IPv6 has emerged as the ideal protocol for the IoT.
- Cloud Computing and Data center: Cloud service providers need to assign independent IP Addresses to massive numbers of virtual machines and containers, and IPv6 provides sufficient address space.
- Industrial Internet and Energy Internet: IPv6 supports precise addressing and management of network elements such as routers, sensors and terminals, facilitating the realization of intelligence.
- Future Network Innovation: The programmable space provided by IPv6 extension headers offers a fundamental platform for emerging network technologies such as SRv6 (Segment Routing IPv6), network slicing, and in-situ flow telemetry.
1.6.4 Challenges and Transition Technologies
Despite its obvious advantages, the full popularization of IPv6 still faces challenges, mainly due to compatibility issues with existing IPv4 networks. The main transition technologies include:
- Dual-stack technology: A network device runs both IPv4 and IPv6 protocol stacks simultaneously.
- Tunneling Technology: Encapsulates IPv6 packets into IPv4 packets to traverse IPv4 networks.
- Protocol conversion technology: such as NAT64, which implements address and protocol conversion between IPv6 and IPv4 networks.

1.7 Summary
IPv6 is not only a fundamental solution to the problem of IP Address exhaustion, but also the foundation for building the next-generation Internet. Its simplified header, built-in security, excellent support for mobility and the Internet of Things, as well as the programmable space reserved for future network innovation, make it an indispensable stage in the upgrading and evolution of the Internet. With the deepening of global deployment, IPv6 will play an increasingly important role in the era of the digital economy.
import network,requests,time,mip,socket
from machine import Pin, WIZNET_PIO_SPI
# ===== W6300-EVB-Pico2 SPI Configuration =====
# According to the configuration in wiznet_init.py
BOARD = "w6300-evb-pico2"
BAUDRATE = 31250000
SCK_PIN = 17
CS_PIN = 16
IO0_PIN = 18
IO1_PIN = 19
IO2_PIN = 20
IO3_PIN = 21
RESET_PIN = 22
# ===== Network Configuration =====
# Static IP configuration (modify according to your network environment)
USE_DHCP = True
STATIC_IP = "192.168.1.50"
STATIC_SN = "255.255.255.0"
STATIC_GW = "192.168.1.1"
STATIC_DNS = "192.168.1.1" # Use Google DNS for improved reliability
def init_wiznet_spi():
"""Directly initialize the WIZnet SPI connection"""
print(f"初始化 {BOARD}...")
# Check whether WIZNET_PIO_SPI is available
try:
from machine import WIZNET_PIO_SPI
except ImportError:
print("错误: 当前固件不支持WIZNET_PIO_SPI")
raise
# Create the pin objects
sck = Pin(SCK_PIN)
cs = Pin(CS_PIN)
io0 = Pin(IO0_PIN)
io1 = Pin(IO1_PIN)
io2 = Pin(IO2_PIN)
io3 = Pin(IO3_PIN)
reset = Pin(RESET_PIN)
# Create the QSPI object (for the W6300)
print("创建WIZNET_PIO_SPI对象...")
spi = WIZNET_PIO_SPI(
baudrate=BAUDRATE,
sck=sck,
cs=cs,
io0=io0,
io1=io1,
io2=io2,
io3=io3
)
# Create the WIZNET6K network interface
print("创建WIZNET6K网络接口...")
nic = network.WIZNET6K(spi, cs, reset)
# Activate the network interface
try:
nic.active(True)
print("网络接口已激活")
except AttributeError:
print("注意: active()方法不支持,继续...")
return nic
def configure_network(nic):
"""Configure network parameters"""
if USE_DHCP:
print("使用DHCP自动获取IP...")
try:
nic.ifconfig("dhcp")
except Exception as e:
print(f"DHCP配置失败: {e}")
return False
else:
print(f"配置静态IP: {STATIC_IP}")
try:
nic.ifconfig((STATIC_IP, STATIC_SN, STATIC_GW, STATIC_DNS))
except Exception as e:
print(f"静态IP配置失败: {e}")
return False
# Wait for the network connection
print("等待网络连接...")
for i in range(10): # Wait up to 10 seconds
if nic.isconnected():
print("网络已连接!")
return True
print(f"等待中... ({i+1}/10)")
time.sleep(1)
print("网络连接超时")
return False
nic = init_wiznet_spi()
configure_network(nic)W6300 Network Connection
W6300 communicates with Pico2 via QSPI, and the pin connections are as follows
W6300 Pin | Pico2 pin |
SCK_PIN | 17 |
CS_PIN | 16 |
IO0_PIN | 18 |
IO1_PIN | 19 |
IO2_PIN | 20 |
IO3_PIN | 21 |
RESET_PIN | 22 |
The code is as follows:
import network,requests,time,mip,socket
from machine import Pin, WIZNET_PIO_SPI
# ===== W6300-EVB-Pico2 SPI Configuration =====
BOARD = "w6300-evb-pico2"
BAUDRATE = 31250000
SCK_PIN = 17
CS_PIN = 16
IO0_PIN = 18
IO1_PIN = 19
IO2_PIN = 20
IO3_PIN = 21
RESET_PIN = 22
# ===== Network Configuration =====
# Static IP configuration (modify according to your network environment)
USE_DHCP = True
STATIC_IP = "192.168.1.50"
STATIC_SN = "255.255.255.0"
STATIC_GW = "192.168.1.1"
STATIC_DNS = "192.168.1.1"
def init_wiznet_spi():
"""Directly initialize the WIZnet SPI connection"""
print(f"初始化 {BOARD}...")
# Check whether WIZNET_PIO_SPI is available
try:
from machine import WIZNET_PIO_SPI
except ImportError:
print("错误: 当前固件不支持WIZNET_PIO_SPI")
raise
# Create the pin objects
sck = Pin(SCK_PIN)
cs = Pin(CS_PIN)
io0 = Pin(IO0_PIN)
io1 = Pin(IO1_PIN)
io2 = Pin(IO2_PIN)
io3 = Pin(IO3_PIN)
reset = Pin(RESET_PIN)
# Create the QSPI object (for the W6300)
print("创建WIZNET_PIO_SPI对象...")
spi = WIZNET_PIO_SPI(
baudrate=BAUDRATE,
sck=sck,
cs=cs,
io0=io0,
io1=io1,
io2=io2,
io3=io3
)
# Create the WIZNET6K network interface
print("创建WIZNET6K网络接口...")
nic = network.WIZNET6K(spi, cs, reset)
# Activate the network interface
try:
nic.active(True)
print("网络接口已激活")
except AttributeError:
print("注意: active()方法不支持,继续...")
return nic
def configure_network(nic):
"""Configure network parameters"""
if USE_DHCP:
print("使用DHCP自动获取IP...")
try:
nic.ifconfig("dhcp")
except Exception as e:
print(f"DHCP配置失败: {e}")
return False
else:
print(f"配置静态IP: {STATIC_IP}")
try:
nic.ifconfig((STATIC_IP, STATIC_SN, STATIC_GW, STATIC_DNS))
except Exception as e:
print(f"静态IP配置失败: {e}")
return False
# Wait for the network connection
print("等待网络连接...")
for i in range(10): # Wait up to 10 seconds
if nic.isconnected():
print("网络已连接!")
return True
print(f"等待中... ({i+1}/10)")
time.sleep(1)
print("网络连接超时")
return False
nic = init_wiznet_spi()
configure_network(nic)You can modify the IP Address configuration according to the actual network, but incorrect configuration will affect usage. It is recommended to directly use USE_DHCP = True to enable DHCP in the test environment.
Experiment
3.1 IPv6 Testing
import network,requests,time,mip,socket
from machine import Pin, WIZNET_PIO_SPI
# ===== W6300-EVB-Pico2 SPI Configuration =====
# According to the configuration in wiznet_init.py
BOARD = "w6300-evb-pico2"
BAUDRATE = 31250000
SCK_PIN = 17
CS_PIN = 16
IO0_PIN = 18
IO1_PIN = 19
IO2_PIN = 20
IO3_PIN = 21
RESET_PIN = 22
# ===== Network Configuration =====
# Static IP configuration (modify according to your network environment)
USE_DHCP = True
STATIC_IP = "192.168.1.50"
STATIC_SN = "255.255.255.0"
STATIC_GW = "192.168.1.1"
STATIC_DNS = "192.168.1.1" # Use Google DNS for improved reliability
def init_wiznet_spi():
"""Directly initialize the WIZnet SPI connection"""
print(f"初始化 {BOARD}...")
# Check whether WIZNET_PIO_SPI is available
try:
from machine import WIZNET_PIO_SPI
except ImportError:
print("错误: 当前固件不支持WIZNET_PIO_SPI")
raise
# Create the pin objects
sck = Pin(SCK_PIN)
cs = Pin(CS_PIN)
io0 = Pin(IO0_PIN)
io1 = Pin(IO1_PIN)
io2 = Pin(IO2_PIN)
io3 = Pin(IO3_PIN)
reset = Pin(RESET_PIN)
# Create the QSPI object (for the W6300)
print("创建WIZNET_PIO_SPI对象...")
spi = WIZNET_PIO_SPI(
baudrate=BAUDRATE,
sck=sck,
cs=cs,
io0=io0,
io1=io1,
io2=io2,
io3=io3
)
# Create the WIZNET6K network interface
print("创建WIZNET6K网络接口...")
nic = network.WIZNET6K(spi, cs, reset)
# Activate the network interface
try:
nic.active(True)
print("网络接口已激活")
except AttributeError:
print("注意: active()方法不支持,继续...")
return nic
def configure_network(nic):
"""Configure network parameters"""
if USE_DHCP:
print("使用DHCP自动获取IP...")
try:
nic.ifconfig("dhcp")
except Exception as e:
print(f"DHCP配置失败: {e}")
return False
else:
print(f"配置静态IP: {STATIC_IP}")
try:
nic.ifconfig((STATIC_IP, STATIC_SN, STATIC_GW, STATIC_DNS))
except Exception as e:
print(f"静态IP配置失败: {e}")
return False
# Wait for the network connection
print("等待网络连接...")
for i in range(10): # Wait up to 10 seconds
if nic.isconnected():
print("网络已连接!")
return True
print(f"等待中... ({i+1}/10)")
time.sleep(1)
print("网络连接超时")
return False
nic = init_wiznet_spi()
configure_network(nic)
# Simplest IPv6 listening test
def test_ipv6_listen():
# 1. Create a pure IPv6 socket
try:
sock = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
print("✓ IPv6 socket 创建成功")
except Exception as e:
print(f"✗ 无法创建 IPv6 socket: {e}")
return False
# 2. Bind to all IPv6 addresses
try:
sock.bind(("::", 80)) # "::" means all IPv6 addresses
print("✓ 绑定到 [::]:80 成功")
except Exception as e:
print(f"✗ 绑定失败: {e}")
sock.close()
return False
# 3. Start listening
sock.listen(1)
print("✓ 正在监听...")
print("\n测试说明:")
print("1. 从电脑尝试: ping6 设备的IPv6地址")
print("2. 如果 ping 不通,可能是防火墙阻止了 ICMP")
print("3. 按 Ctrl+C 停止")
# 5. Keep listening
try:
while True:
time.sleep(1) # Do not accept connections, just stay in the listening state
except KeyboardInterrupt:
print("\n✓ 测试结束")
finally:
sock.close()
return True
# Run the test
test_ipv6_listen()
3.2 IPv6 flask-like webserver
Go to the upypi website to download the microflask library, or use mip
The version specified for this experiment is: https://upypi.net/zh/pkgs/microflask/0.0.20260505
0.0.20260505
local installation
mpremote mip install https://upypi.net/pkgs/microflask/0.0.20260505
Remote Installation
mip.install(" https://upypi.net/pkgs/microflask/0.0.20260505 ")
microflask.py
#Author : iw0雨渊(Gitee:@wth_iw0 GitHub:@iw0_wth)
#Date : 2026.5.05
#Description : MicroFlask is a Flask-like web framework engineered to streamline the migration of Flask-based projects.
#Copyright © 2026 iw0雨渊. All rights reserved.
#Version : 0.0.20260505
#License : MIT License
#Contact : EMAIL:tianqi2021_001@163.com
#Github : https://github.com/iw0-wth
__version__ = '0.0.20260505'#test-ipv6
"""
MicroFlask Web Framework
Synchronous version of MicroFlask, largely compatible with Flask, runs on both mpy and py, and supports custom dynamic routing rules
This project uses micropython-easyweb as reference: https://github.com/funnygeeker/micropython-easyweb
This project integrates utemplate as third-party engine: https://github.com/pfalcon/utemplate/
"""
import os
import sys
import re
import socket
import binascii
try:
from utemplate import source, compiled, recompile
UTEMPLATE_AVAILABLE = True
except ImportError:
UTEMPLATE_AVAILABLE = False
try:
import ujson as json # MicroPython
except Exception: # pragma: no cover
import json # type: ignore
try:
import micropython # MicroPython
except Exception: # pragma: no cover
micropython = None
STRICT_MODE = True
#Compatibility functions
def _schedule(func, arg):
"""Compatible with micropython.schedule; called directly under CPython."""
if micropython is not None and hasattr(micropython, "schedule"):
micropython.schedule(func, arg)
else: # pragma: no cover
func(arg)
def groups(match):
i = 1
return_tuple = tuple()
while True:
try:
return_tuple += (match.group(i),)
i += 1
except Exception:
break
return return_tuple
def escape(text):
"""Manual implementation replacing re.escape"""
special_chars = r"\^$*+?.()|{}[]"
return "".join(["\\" + char if char in special_chars else char for char in text])
class ImmutableMultiDict(dict):
"""Compatible with older versions of mpy"""
def get(self, key, default=None):
if key in self:
return super().get(key)
return default
#External extensible rendering engine
class TemplateEngine:
"""Template engine base class, defining a unified rendering interface"""
def render(self, template_content: str, context: dict) -> str:
"""
Core method for rendering a template
Args:
template_content: template content string
context: Context variable dictionary
Returns:
Rendered string
"""
raise NotImplementedError("子类必须实现此方法")
def render_file(self, template_path: str, context: dict) -> str:
"""
Convenience method for rendering a template from a file
Args:
template_path: template file path
context: Context variable dictionary
Returns:
Rendered string
"""
try:
# Try reading from the templates directory
with open(f"templates/{template_path}", "rb") as f:
content = f.read().decode("utf-8")
except OSError:
# Try reading from the direct path
with open(template_path, "rb") as f:
content = f.read().decode("utf-8")
return self.render(content, context)
class ExpressionTemplateEngine(TemplateEngine):
"""Template engine supporting expression evaluation"""
def render(self, template_content: str, context: dict) -> str:
def eval_expression(match):
expression = match.group(1).strip()
try:
env = globals()
env.update(context)
result = eval(expression, {"__builtins__": {}}, env)
return str(result)
except Exception:
# Return the original expression if evaluation fails
return match.group(0)
# Use a regex to replace all {{ expression }}
return re.sub(r'{{\s*(.*?)\s*}}', eval_expression, template_content)
class SimpleTemplateEngine(TemplateEngine):
"""Template engine using simple string replacement"""
def render(self, template_content: str, context: dict) -> str:
"""Render the template using string replacement"""
result = template_content
for key, value in context.items():
placeholder = "{{ %s }}" % key
result = result.replace(placeholder, str(value))
return result
class ThirdPartyTemplateAdapter(TemplateEngine):
"""Third-party template engine adapter template"""
def __init__(self, engine_instance, render_method_name="render"):
"""
Initialize the adapter
Args:
engine_instance: third-party template engine instance
render_method_name: render method name, default is 'render'
"""
self.engine = engine_instance
self.render_method = getattr(engine_instance, render_method_name)
def render(self, template_content: str, context: dict) -> str:
"""Call the third-party engine's render method"""
return self.render_method(template_content, **context)
def render_file(self, template_path: str, context: dict) -> str:
"""Override the file rendering method to fit the third-party engine's file loading approach"""
# Some third-party engines may have their own file loading logic
if hasattr(self.engine, 'render_file'):
return self.engine.render_file(template_path, **context)
# Otherwise use the base class's default implementation
return super().render_file(template_path, context)
def create_template_adapter(render_func, file_render_func=None):
"""Create a functional template engine adapter"""
class FunctionalTemplateEngine(TemplateEngine):
def render(self, template_content: str, context: dict) -> str:
return render_func(template_content, **context)
def render_file(self, template_path: str, context: dict) -> str:
if file_render_func:
return file_render_func(template_path, **context)
# Fall back to default file loading + rendering
with open(template_path, "r", encoding="utf-8") as f:
content = f.read()
return render_func(content, **context)
return FunctionalTemplateEngine()
class UTemplateEngine(TemplateEngine):
"""utemplate template engine adapter"""
def __init__(self, pkg=None, dir="templates", loader_type="source", auto_recompile=True):
"""
Initialize the utemplate engine
Args:
pkg: package name, usually __name__
dir: template directory
loader_type: loader type, one of "source", "compiled", "recompile"
auto_recompile: whether to recompile automatically (only effective for recompile)
"""
if not UTEMPLATE_AVAILABLE:
raise ImportError("utemplate is not installed. ")
self.pkg = pkg
self.dir = dir
#Because mpy imports start from the root directory, template file imports would fail, so a relative directory is added
if self.dir not in sys.path:
sys.path.append(self.dir)
# Create the corresponding loader according to loader_type
if loader_type == "compiled":
self.loader = compiled.Loader(pkg, dir)
elif loader_type == "recompile":
self.loader = recompile.Loader(pkg, dir)
else: # source is the default
self.loader = source.Loader(pkg, dir)
# Cache loaded template functions
self._template_cache = {}
def _get_template(self, template_name):
"""Get the template function, with caching support"""
# Remove the dot from the extension and replace it with an underscore
cache_key = template_name.replace(".", "_")
if cache_key not in self._template_cache:
# Get the template function from the loader
render_func = self.loader.load(template_name)
self._template_cache[cache_key] = render_func
return self._template_cache[cache_key]
def render(self, template_content: str, context: dict) -> str:
"""
Render a template content string
Note: utemplate is mainly designed for file templates; a basic implementation is provided here
But utemplate's advantage lies in compiling file templates, so this method may not be optimal
"""
# Since utemplate is mainly designed for file templates, we use a simple fallback for string rendering
result = template_content
# Simple variable substitution
for key, value in context.items():
placeholder = "{{ " + str(key) + " }}"
result = result.replace(placeholder, str(value))
return result
def render_file(self, template_path: str, context: dict) -> str:
"""
Render a template from a file - this is the main way to use utemplate
"""
# Get the template function
render_func = self._get_template(template_path)
try:
# Call the template function, which returns a generator
generator = render_func(**context)
# Collect all fragments from the generator
parts = []
for chunk in generator:
if chunk is not None:
parts.append(str(chunk))
return "".join(parts)
except Exception as e:
# If rendering fails, provide detailed error information
error_msg = f"UTemplate渲染错误: {e}\n"
error_msg += f"模板: {template_path}\n"
error_msg += f"上下文键: {list(context.keys())}"
raise RuntimeError(error_msg) from e
def clear_cache(self):
"""Clear the template cache"""
self._template_cache.clear()
#External extensible dynamic routing rules
class BaseConverter:
"""Route converter base class, modeled on Flask's werkzeug.routing.BaseConverter"""
# Regular expression part used when the converter matches a variable
# Subclasses can override this attribute
regex = "[^/]+"
# Arguments the converter accepts in the URL (for example, in <int:num>, "int" is the name and there are no arguments)
# For <re(r"\d+"):var>, the name is "re" and the argument is (r"\d+",)
def __init__(self, map, *args, **kwargs):
"""
Args:
map: reserved parameter, passed in as url_map for compatibility with the Flask API
*args: arguments from inside the parentheses in the route definition, such as r"\d+" in <re(r"\d+"):id>
"""
self.map = map
self.args = args
self.kwargs = kwargs
def to_python(self, value: str):
"""
Convert the string value in the URL to a Python object (passed to the view function).
Returns a string by default; subclasses can override it to perform type conversion.
"""
return value
def to_url(self, value) -> str:
"""
Convert a Python object back to a string for the URL.
Uses str() by default; subclasses can override.
"""
return str(value)
# ---------------- Default converter definitions ----------------
class StringConverter(BaseConverter):
"""String converter, the default type"""
pass # Use the base class's regex and to_python
class IntConverter(BaseConverter):
"""Integer converter"""
regex = r"[-+]?\d+"
if STRICT_MODE:
regex = r"-?\d+"
def to_python(self, value: str):
return int(value)
class FloatConverter(BaseConverter):
"""Float converter"""
regex = r"[-+]?\d+\.\d+|[+-]?\d+"
if STRICT_MODE:
regex = r"-?\d+\.\d+"
def to_python(self, value: str):
return float(value)
class PathConverter(BaseConverter):
"""Path converter, matches the remainder including slashes"""
regex = ".+"
def to_python(self, value: str):
return value
class PartConverter(BaseConverter):
"""part converter, matches a non-empty path segment, excluding slashes"""
regex = ".+?"
class ReConverter(BaseConverter):
def __init__(self, map, reg):
super().__init__(map)
self.regex = reg
class BoolConverter(BaseConverter):
"""bool converter"""
regex = r"[tT][rR][uU][eE]|[fF][aA][lL][sS][eE]|[yY][eE][sS]|[nN][oO]|1|0"
if STRICT_MODE:
regex = r"[tT]rue|[fF]alse|[yY]es|[nN]o|1|0"
def to_python(self, value: str):
return str(value).lower() in ("true", "1", "yes")
#Reference list
FILE_TYPE = ImmutableMultiDict(
{
".txt": "text/plain",
".htm": "text/html",
".html": "text/html",
".css": "text/css",
".csv": "text/csv",
".js": "application/javascript",
".xml": "application/xml",
".xhtml": "application/xhtml+xml",
".json": "application/json",
".zip": "application/zip",
".pdf": "application/pdf",
".ts": "application/typescript",
".woff": "font/woff",
".woff2": "font/woff2",
".ttf": "font/ttf",
".otf": "font/otf",
".jpg": "image/jpeg",
".jpeg": "image/jpeg",
".png": "image/png",
".gif": "image/gif",
".svg": "image/svg+xml",
".ico": "image/x-icon",
}
)
STATUS_CODE = ImmutableMultiDict(
{
100: "Continue",
101: "Switching Protocols",
102: "Processing",
200: "OK",
201: "Created",
202: "Accepted",
203: "Non-Authoritative Information",
204: "No Content",
205: "Reset Content",
206: "Partial Content",
207: "Multi-Status",
208: "Already Reported",
226: "IM Used",
300: "Multiple Choices",
301: "Moved Permanently",
302: "Found",
303: "See Other",
304: "Not Modified",
305: "Use Proxy",
307: "Temporary Redirect",
308: "Permanent Redirect",
400: "Bad Request",
401: "Unauthorized",
402: "Payment Required",
403: "Forbidden",
404: "Not Found",
405: "Method Not Allowed",
406: "Not Acceptable",
407: "Proxy Authentication Required",
408: "Request Timeout",
409: "Conflict",
410: "Gone",
411: "Length Required",
412: "Precondition Failed",
413: "Payload Too Large",
414: "URI Too Long",
415: "Unsupported Media Type",
416: "Range Not Satisfiable",
417: "Expectation Failed",
418: "I'm a teapot",
422: "Unprocessable Entity",
423: "Locked",
424: "Failed Dependency",
426: "Upgrade Required",
428: "Precondition Required",
429: "Too Many Requests",
431: "Request Header Fields Too Large",
451: "Unavailable For Legal Reasons",
500: "Internal Server Error",
501: "Not Implemented",
502: "Bad Gateway",
503: "Service Unavailable",
504: "Gateway Timeout",
505: "HTTP Version Not Supported",
506: "Variant Also Negotiates",
507: "Insufficient Storage",
508: "Loop Detected",
510: "Not Extended",
511: "Network Authentication Required",
}
)
# ========= URL encoding/decoding (easyweb.py) =========
def url_encode(url):
encoded_url = ""
for char in url:
if char.isalpha() or char.isdigit() or char in ("-", ".", "_", "~"):
encoded_url += char
elif char == " ":
encoded_url += "%20" # A space is usually encoded as %20
else:
# Encode each byte
try:
utf8_bytes = char.encode("utf-8")
for byte in utf8_bytes:
encoded_url += "%" + f"{byte:02X}" # Two uppercase hex digits
except:
# Encoding failed, use the replacement character
encoded_url += "%EF%BF%BD" # UTF-8 encoding of the Unicode replacement character
return encoded_url
def url_decode(encoded_url):
"""URL decoding"""
encoded_url = encoded_url.replace("+", " ")
if "%" not in encoded_url:
return encoded_url
blocks = encoded_url.split("%")
decoded_url = blocks[0]
buffer = ""
for b in blocks[1:]:
if len(b) == 2:
buffer += b[:2]
else:
decoded_url += binascii.unhexlify(buffer + b[:2]).decode("utf-8")
buffer = ""
decoded_url += b[2:]
if buffer:
decoded_url += binascii.unhexlify(buffer).decode("utf-8")
return decoded_url
def _is_generator(obj):
# Compatible with MicroPython: check using the "generator type" (borrowed from easyweb.py)
def _g():
yield 0
return isinstance(obj, type(_g()))
def _is_streaming_body(body):
if body is None:
return False
if isinstance(body, (bytes, str, dict)):
return False
return _is_generator(body) or hasattr(body, "__iter__")
def _to_bytes(x, charset="utf-8"):
if x is None:
return b""
if isinstance(x, bytes):
return x
if isinstance(x, str):
return x.encode(charset)
# Allow a generator to yield a dict as a header patch
return str(x).encode(charset)
class Request:
def __init__(self, method="GET", full_path="/", protocol="HTTP/1.1", headers=None, body=b""):
self.method = method or "GET"
self.full_path = full_path or "/"
self.protocol = protocol or "HTTP/1.1"
self.headers = ImmutableMultiDict(headers or {})
self.body = body if body is not None else b""
# Parse the path: path is used for route matching (must be URL-decoded)
raw_path = self.full_path.split("?", 1)[0]
self.path = url_decode(raw_path)
self.view_args = ImmutableMultiDict({})
self._url = None
self._args = None
self._form = None
self._json = None
self._cookies = None
@property
def host(self):
return self.headers.get("Host")
@property
def url(self):
if self._url is None:
host = self.host
if host:
self._url = "http://{}{}".format(host, self.full_path)
return self._url
@property
def args(self):
if self._args is None:
args = {}
try:
if "?" in self.full_path:
query_str = self.full_path.split("?", 1)[1].rstrip("&")
else:
query_str = ""
if query_str:
for arg_pair in query_str.split("&"):
if not arg_pair:
continue
if "=" in arg_pair:
key, value = arg_pair.split("=", 1)
else:
key, value = arg_pair, ""
args[url_decode(key)] = url_decode(value)
except Exception:
args = {}
self._args = ImmutableMultiDict(args)
return self._args
@property
def json(self):
if self._json is None:
try:
self._json = json.loads(self.body)
except Exception:
self._json = None
return self._json
@property
def form(self):
if self._form is None:
try:
ct = self.headers.get("Content-Type", "") or ""
if "application/x-www-form-urlencoded" not in ct:
self._form = None
return None
items = (self.body or b"").decode("utf-8").split("&")
form = {}
for item in items:
if not item:
continue
if "=" in item:
k, v = item.split("=", 1)
else:
k, v = item, ""
k = url_decode(k)
v = None if v == "" else url_decode(v)
form[k] = v
self._form = ImmutableMultiDict(form)
except Exception:
self._form = None
return self._form
@property
def cookies(self):
if self._cookies is None:
cookies = {}
try:
raw = self.headers.get("Cookie")
if raw:
items = raw.split(";")
for item in items:
item = item.strip()
if "=" in item:
k, v = item.split("=", 1)
cookies[url_decode(k)] = url_decode(v)
except Exception:
cookies = {}
self._cookies = ImmutableMultiDict(cookies)
return self._cookies
class Response:
_default_template_engine = None
def __init__(self, content=b"", status=200, headers=None, mimetype=None, content_type=None):
self.status = int(status or 200)
self.reason = STATUS_CODE.get(self.status, "Undefined")
self.headers = {}
if headers:
if isinstance(headers, dict):
self.headers.update(headers)
else:
for k, v in headers:
self.headers[k] = v
self._cookies = [] # list[str] like: Set-Cookie: ...
if mimetype and not content_type:
content_type = mimetype
self._explicit_content_type = content_type
self.content = content
def set_cookie(self, name, value="", max_age=None, path="/"):
if max_age is None:
max_age_part = ""
else:
max_age_part = "; Max-Age={}".format(int(max_age))
path_part = "" if path is None else "; Path={}".format(path)
line = "Set-Cookie: {}={}{}{}".format(
url_encode(str(name)), url_encode(str(value)), max_age_part, path_part
)
self._cookies.append(line)
@classmethod
def set_default_template_engine(cls, engine):
"""Set the default template engine"""
cls._default_template_engine = engine
@classmethod
def render_template(cls, template_path, *args,
template_engine=None, # A specific engine can be passed in
**kwargs):
"""Enhanced template rendering method that supports multiple engines"""
# Determine the context
def _ctx(*args, **kwargs):
if args and isinstance(args[0], dict):
return args[0]
return kwargs
context = _ctx(*args, **kwargs)
# Determine which engine to use
engine = template_engine or cls._default_template_engine
# If no engine is set, use the expression engine as the default
if engine is None:
engine = ExpressionTemplateEngine()
# The default engine instance can be cached
cls._default_template_engine = engine
try:
# Render using the engine
content = engine.render_file(template_path, context)
return cls(content, content_type="text/html; charset=utf-8")
except Exception as e:
return cls(f"Template Error: {e}", status=500)
# Add a method for using string templates directly
@classmethod
def render_string(cls, template_string, *args,
template_engine=None, **kwargs):
"""Render a string template"""
# Determine the context
def _ctx(*args, **kwargs):
if args and isinstance(args[0], dict):
return args[0]
return kwargs
context = _ctx(*args, **kwargs) if args and isinstance(args[0], dict) else kwargs
engine = template_engine or cls._default_template_engine
if engine is None:
engine = ExpressionTemplateEngine()
cls._default_template_engine = engine
try:
content = engine.render(template_string, context)
return cls(content, content_type="text/html; charset=utf-8")
except Exception as e:
return cls(f"Template Error: {e}", status=500)
def _finalize_headers(self, body_bytes=None, streaming=False):
# Default Content-Type policy
if self._explicit_content_type:
# If the user explicitly specified a Content-Type but no charset and it is a text type, add one
ct = self._explicit_content_type.lower()
if ct.startswith('text/') and 'charset=' not in ct:
self._explicit_content_type = f"{self._explicit_content_type}; charset=utf-8"
self.headers.setdefault("Content-Type", self._explicit_content_type)
else:
# If none was explicitly specified, set a default based on the content type
if isinstance(self.content, str):
# Strings default to HTML, with UTF-8 forced
self.headers.setdefault("Content-Type", "text/html; charset=utf-8")
elif isinstance(self.content, dict):
# JSON response
self.headers.setdefault("Content-Type", "application/json")
elif isinstance(self.content, list):
# JSON response
self.headers.setdefault("Content-Type", "application/json")
else:
# Other text content
self.headers.setdefault("Content-Type", "text/plain; charset=utf-8")
self.headers.setdefault("Connection", "close")
if (not streaming) and (body_bytes is not None):
self.headers.setdefault("Content-Length", str(len(body_bytes)))
# Add other headers related to UTF-8 encoding
self.headers.setdefault("Content-Encoding", "identity")
def _status_line(self):
return "HTTP/1.1 {} {}\r\n".format(self.status, self.reason).encode("utf-8")
def _headers_bytes(self):
# headers
lines = []
for k, v in self.headers.items():
lines.append("{}: {}".format(k, v))
# cookies
for c in self._cookies:
lines.append(c)
return ("\r\n".join(lines) + "\r\n\r\n").encode("utf-8")
def iter_chunks(self):
"""
Unified "response byte stream" iterator:
- Non-streaming: status_line + headers + body
- Streaming: status_line + headers + (chunks...)
If the first yield of the generator is a dict, it is used to add to the headers (easyweb style).
"""
streaming = _is_streaming_body(self.content)
# Non-streaming: prepare the body bytes and set the headers
if not streaming:
body = self.content
if isinstance(body, dict):
body = json.dumps(body)
if isinstance(body, list):
body = json.dumps(body)
body_bytes = _to_bytes(body)
self._finalize_headers(body_bytes=body_bytes, streaming=False)
yield self._status_line()
yield self._headers_bytes()
if body_bytes:
yield body_bytes
return
# Streaming: peek at the first chunk (may be a headers dict)
it = iter(self.content)
first_item = None
has_first = False
try:
first_item = next(it)
has_first = True
except Exception:
has_first = False
if has_first and isinstance(first_item, dict):
self.headers.update(first_item)
first_item = None
has_first = False
self._finalize_headers(body_bytes=None, streaming=True)
yield self._status_line()
yield self._headers_bytes()
if has_first and first_item is not None:
b = _to_bytes(first_item)
if b:
yield b
for item in it:
if item is None:
continue
b = _to_bytes(item)
if b:
yield b
def build(self):
"""Only for quick concatenation in non-streaming mode (use iter_chunks for streaming)."""
if _is_streaming_body(self.content):
# Avoid concatenating the whole generator into memory
data = b"".join([chunk for chunk in self.iter_chunks()])
return data
body = self.content
if isinstance(body, dict):
body = json.dumps(body)
if isinstance(body, list):
body = json.dumps(body)
body_bytes = _to_bytes(body)
self._finalize_headers(body_bytes=body_bytes, streaming=False)
return self._status_line() + self._headers_bytes() + body_bytes
def make_response(content=b"", status=200, headers=None):
if isinstance(content, Response):
if status is not None:
content.status = int(status)
content.reason = STATUS_CODE.get(content.status, "Undefined")
if headers:
if isinstance(headers, dict):
content.headers.update(headers)
else:
for k, v in headers:
content.headers[k] = v
return content
if isinstance(content, tuple):
# (body, status) or (body, status, headers)
if len(content) == 2:
return Response(content[0], status=content[1])
if len(content) >= 3:
return Response(content[0], status=content[1], headers=content[2])
return Response(content, status=status, headers=headers)
class Application:
def __init__(self, static_folder="static/", static_url_path="/static/"):
self.routes = []
self.static_routes = {}
self.static_folder = static_folder
self.static_url_path = static_url_path
# Initialize the URL map and the converters dictionary
# Simulate Flask's url_map
class UrlMap:
def __init__(self):
self.converters = {}
self.url_map = UrlMap()
self._register_default_converters()
def _register_default_converters(self):
"""Register all default converters"""
self.url_map.converters.update({
'string': StringConverter,
'int': IntConverter,
'float': FloatConverter,
'path': PathConverter,
'part': PartConverter,
're': ReConverter, # Refactored re converter
'bool': BoolConverter
})
def _compile_route(self, path: str):
"""
Compile the route path, supporting the Flask-style <converter_name(args):variable_name> syntax.
Returns: (compiled_regex_pattern, converters_dict, param_names_list)
"""
# Modified regular expression, using plain capture groups instead of named capture groups
# Group 1: converter name
# Group 2: arguments in parentheses
# Group 3: variable name
route_param_pattern = re.compile(
r'<(?:([a-zA-Z_][a-zA-Z0-9_]*)(?:\(([^)]*)\))?:)?([a-zA-Z_][a-zA-Z0-9_]*)>'
)
param_names = []
converters = {} # Holds {variable_name: converter_instance}
regex_parts = []
# Split the path by slashes, but note that the path converter consumes all remaining parts
segments = path.split('/')
for segment in segments:
if not segment:
regex_parts.append('') # For the leading empty segment
continue
# Try to match a dynamic segment
match = route_param_pattern.match(segment)
if match:
# Get the full matched string
matched_str = match.group(0)
# Check whether the whole segment was matched (MicroPython-compatible method)
if matched_str == segment:
# This is a dynamic parameter segment
converter_name = match.group(1) # Index 1 is the converter name
args_string = match.group(2) # Index 2 is the arguments
variable_name = match.group(3) # Index 3 is the variable name
if variable_name in param_names:
raise ValueError(f"Duplicate variable name '{variable_name}' in route '{path}'")
param_names.append(variable_name)
# 1. Determine the converter class
if converter_name is None:
converter_name = 'string' # Default converter
converter_class = self.url_map.converters.get(converter_name)
if converter_class is None:
raise ValueError(f"Unknown converter '{converter_name}' in route '{path}'. "+
f"Available converters: {list(self.url_map.converters.keys())}")
# 2. Parse the arguments (if present)
args = ()
kwargs = {}
if args_string:
# This is a simplified argument parser, mainly handling single-string arguments like re(r'...')
try:
# Try to parse a tuple with eval, but in a controlled environment (arguments come from developer-defined routes)
parsed_args = eval(f'({args_string},)', {}, {})
if isinstance(parsed_args, tuple):
args = parsed_args
except Exception:
# If eval fails, treat the whole args_string as a single string argument
args = (args_string.strip(),)
# 3. Create the converter instance
converter_instance = converter_class(self.url_map, *args, **kwargs)
converters[variable_name] = converter_instance
# 4. Get the regex part of this converter and add it to the path
regex_part = f"({converter_instance.regex})"
regex_parts.append(regex_part)
# 5. If the 'path' converter is encountered, it is the last part; break out of the loop
if converter_name == 'path':
# Make sure path is the last converter
if segments.index(segment) != len(segments) - 1:
raise ValueError(f"Path converter '{segment}' must be the last part in route '{path}'")
# For the path converter, we no longer join the remaining hard-coded parts
break
continue # Dynamic segment handled, continue to the next segment
# If we get here, it is not a dynamic parameter segment but a static text segment
regex_parts.append(escape(segment))
# Build the full regular expression
regex_pattern = "^" + "/".join(regex_parts) + "$"
# Clean up double slashes (may occur when there are empty segments)
regex_pattern = regex_pattern.replace("//", "/")
try:
compiled_pattern = re.compile(regex_pattern)
except re.error as e:
raise ValueError(f"Invalid regex pattern for route '{path}': {e}") from e
return compiled_pattern, converters, param_names
def route(self, path, methods=None):
if methods is None:
methods = ["GET"]
# Receive three return values here
compiled_pattern, converters, param_names = self._compile_route(path)
def decorator(func):
for method in methods:
m = (method or "GET").upper()
if "<" in path:
# Store converters and param_names together
self.routes.append((m, compiled_pattern, converters, param_names, func))
else:
self.static_routes[(m, path)] = func
return func
return decorator
def add_route(self, path, handler, methods=None):
if methods is None:
methods = ["GET"]
# Receive three return values here
compiled_pattern, converters, param_names = self._compile_route(path)
for method in methods:
m = (method or "GET").upper()
if "<" in path:
# Store converters and param_names together
self.routes.append((m, compiled_pattern, converters, param_names, handler))
else:
self.static_routes[(m, path)] = handler
def run(self, host="0.0.0.0", port=80, debug=False, **kwargs):
server = HTTPServer(self, host=host, port=port, **kwargs)
server.start()
def _call_view(self, view_func, req):
try:
argc = view_func.__code__.co_argcount
except Exception:
argc = 1
if argc == 0:
return view_func()
return view_func(req)
def _serve_static_file(self, req):
if not req.path.startswith(self.static_url_path):
return None
rel = req.path[len(self.static_url_path) :]
if rel.startswith("/"):
rel = rel[1:]
if ".." in rel:
return Response("Forbidden", status=403)
file_path = self.static_folder + rel
try:
content_type = "application/octet-stream"
for ext, ct in FILE_TYPE.items():
if file_path.endswith(ext):
content_type = ct
break
with open(file_path, "rb") as f:
return Response(f.read(), content_type=content_type)
except Exception:
return None
def handle_request(self, req):
# Static files
static_resp = self._serve_static_file(req)
if static_resp is not None:
return static_resp
# Static route
handler = self.static_routes.get((req.method, req.path))
# Dynamic route
if not handler:
for method, pattern, converters, param_names, view_func in self.routes: # Note: what is unpacked here has changed
if method != req.method:
continue
match = pattern.match(req.path)
if match:
# Extract the matched string groups
matched_values = groups(match)
view_args_dict = {}
# Use the converter to convert the string to a Python value
for var_name, raw_value in zip(param_names, matched_values):
converter = converters.get(var_name)
if converter:
try:
view_args_dict[var_name] = converter.to_python(raw_value)
except Exception as e:
# Conversion failed, e.g. int('abc')
# You can choose to log it or skip this route
print(f"[web] Converter error for '{var_name}': {e}")
view_args_dict = None
break
else:
# No converter, keep it as a string
view_args_dict[var_name] = raw_value
if view_args_dict is None:
continue # Conversion failed, try the next route
req.view_args = ImmutableMultiDict(view_args_dict)
handler = view_func
break
if not handler:
return Response("Not Found", status=404)
try:
res = self._call_view(handler, req)
if isinstance(res, Response):
return res
if isinstance(res, tuple):
return make_response(res)
return Response(res)
except Exception as e:
return Response("Error1: {}".format(e), status=500)
class HTTPServer:
def __init__(self, app, host="0.0.0.0", port=80, max_request_length=8192, header_chunk_size=256):
self.app = app
self.host = host
self.port = int(port)
self.max_request_length = int(max_request_length)
self.header_chunk_size = int(header_chunk_size)
# ipv6
if self.host == "::":
try:
# Try to create an IPv6 socket
self.sock = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
print(f"[web] Using IPv6 socket (AF_INET6)")
except (AttributeError, OSError) as e:
print(f"[web] Warning: Cannot create IPv6 socket: {e}")
print("[web] Falling back to IPv4 socket")
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
else:
# Use IPv4 by default
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Set socket options
try:
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
except Exception:
pass
def start(self):
try:
self.sock.bind((self.host, self.port))
self.sock.listen(5)
# Display the correct address format
if ":" in self.host and not self.host.startswith("["):
# IPv6 address, displayed in square brackets
print("[web] Server running on [{}]:{}".format(self.host, self.port))
else:
print("[web] Server running on {}:{}".format(self.host, self.port))
if sys.implementation.name == 'micropython':
print("[web] If you have enabled AP or STA mode, you can access the server with the corresponding IP address.")
print("[web] In AP mode, it is recommended to use the 'microdns' library to enable accessing by any website address.")
while True:
conn, addr = self.sock.accept()
_schedule(self.handle_connection, conn)
except Exception as e:
print(f"[web] Failed to start server: {e}")
raise
def _send_all(self, conn, data):
# MicroPython sockets may not have sendall
mv = memoryview(data)
total = len(mv)
sent = 0
while sent < total:
n = conn.send(mv[sent:])
if n is None:
n = 0
sent += n
def _read_until(self, conn, marker=b"\r\n\r\n"):
buf = b""
while True:
chunk = conn.recv(self.header_chunk_size)
if not chunk:
break
buf += chunk
if marker in buf:
return buf
if len(buf) > self.max_request_length:
raise Exception("Request too large")
return buf
def _parse_header_bytes(self, header_bytes):
# header_bytes: bytes up to \r\n\r\n (may include some body tail)
header_end = header_bytes.find(b"\r\n\r\n")
if header_end < 0:
raise Exception("Bad request")
head = header_bytes[:header_end].decode("utf-8")
rest = header_bytes[header_end + 4 :]
lines = head.split("\r\n")
if not lines:
raise Exception("Bad request")
req_line = lines[0].split(" ")
if len(req_line) < 3:
raise Exception("Bad request line")
method, full_path, protocol = req_line[0], req_line[1], req_line[2]
headers = {}
for line in lines[1:]:
if not line:
continue
if ": " in line:
k, v = line.split(": ", 1)
elif ":" in line:
k, v = line.split(":", 1)
else:
continue
headers[k.strip()] = v.strip()
return method.upper(), full_path, protocol, headers, rest
def handle_connection(self, conn):
try:
head_and_maybe_body = self._read_until(conn)
method, full_path, protocol, headers, body0 = self._parse_header_bytes(
head_and_maybe_body
)
content_length = 0
try:
content_length = int(headers.get("Content-Length", "0") or "0")
except Exception:
content_length = 0
body = body0 or b""
remain = content_length - len(body)
while remain > 0:
chunk = conn.recv(min(1024, remain))
if not chunk:
break
body += chunk
remain -= len(chunk)
req = Request(method=method, full_path=full_path, protocol=protocol, headers=headers, body=body)
resp = self.app.handle_request(req)
if not isinstance(resp, Response):
resp = Response(resp)
for chunk in resp.iter_chunks():
if chunk:
self._send_all(conn, chunk)
except Exception as e:
print("[web]Error:", e)
try:
resp = Response("Internal Server Error", status=500)
self._send_all(conn, resp.build())
except Exception:
pass
finally:
try:
conn.close()
except Exception:
pass
def Flask(import_name=None, **kwargs):
return Application(**kwargs)
def render_template(template_path, *args, **kwargs):
return Response.render_template(template_path, *args, **kwargs)
def render_template_string(template_string, *args, **kwargs):
return Response.render_string(template_string, *args, **kwargs)
def redirect(url):
resp = Response("", status=302)
resp.headers["Location"] = url
return resp
def _self_test():
# 1) query url_decode
req = Request(method="GET", full_path="/hello?name=%E4%B8%AD%E6%96%87&x=1+2", headers={"Host": "a"})
assert req.path == "/hello"
assert req.args.get("name") == "中文"
assert req.args.get("x") == "1 2"
assert req.url == "http://a/hello?name=%E4%B8%AD%E6%96%87&x=1+2"
# 2) cookies decode
req2 = Request(headers={"Cookie": "a=1; b=%E4%B8%AD%E6%96%87"})
assert req2.cookies.get("b") == "中文"
# 3) Response cookie encode
r = Response("ok")
r.set_cookie("b", "中文", max_age=10)
bs = b"".join(r.iter_chunks())
assert b"Set-Cookie:" in bs
# 4) streaming response with header patch
def gen():
yield {"Content-Type": "text/plain"}
yield b"1"
yield b"2"
r2 = Response(gen())
out = b"".join(r2.iter_chunks())
assert b"Content-Type: text/plain" in out
assert out.endswith(b"12")
# 5) dynamic route + type conversion
app = Flask(__name__)
@app.route("/u/<int:uid>", methods=["GET"])
def u(req):
return req.view_args.get("uid")
resp = app.handle_request(Request(method="GET", full_path="/u/12"))
assert b"".join(resp.iter_chunks()).endswith(b"12")
# 6) POST form
@app.route("/form", methods=["POST"])
def form(req):
return req.form.get("b")
body = b"a=1&b=%E4%B8%AD"
resp2 = app.handle_request(
Request(
method="POST",
full_path="/form",
headers={"Content-Type": "application/x-www-form-urlencoded", "Content-Length": str(len(body))},
body=body,
)
)
assert b"".join(resp2.iter_chunks()).endswith("中".encode("utf-8"))
# 7) POST JSON
@app.route("/json", methods=["POST"])
def j(req):
return req.json.get("a")
bodyj = b'{"a":1}'
resp3 = app.handle_request(
Request(
method="POST",
full_path="/json",
headers={"Content-Type": "application/json", "Content-Length": str(len(bodyj))},
body=bodyj,
)
)
assert b"".join(resp3.iter_chunks()).endswith(b"1")
# 8) static file
try:
os.mkdir("static")
except Exception:
pass
try:
with open("static/_t.txt", "wb") as f:
f.write(b"hi")
resp4 = app.handle_request(Request(method="GET", full_path="/static/_t.txt"))
data4 = b"".join(resp4.iter_chunks())
assert data4.endswith(b"hi")
finally:
try:
os.remove("static/_t.txt")
except Exception:
pass
return True
if __name__ == "__main__": # pragma: no cover
print(_self_test())
This library adopts a flask-like API and is compatible with Flask syntax in most scenarios. A minor drawback, however, is that Flask's context manager for global request is somewhat too resource-intensive for embedded environments, so we ultimately did not adopt the context manager solution.
This also leads to the fact that the function requires only one variable (i. e. the original request) to be passed in; it is no longer global here, but the flexibility of directly using get variables is also lost.
from microflask import *
app = Flask(__name__)
@app.route('/')
def hello(request):
return "Hello, MicroFlask!"https://upypi.net/zh/pkgs/microflask/0.0.20260505
README.md can be viewed here, more features can be shown to pay attention to the github repository, there are many demos
The page for this test is one of the demos:
import gc
gc.collect()
import os
import re
import sys
import time
import json
import hashlib
# Import the framework from the provided file
from microflask import *
# Create the Flask app
app = Flask(
static_folder="static/",
static_url_path="/static/",
)
import network,requests,time,mip
from machine import Pin, WIZNET_PIO_SPI
# ===== W6300-EVB-Pico2 SPI Configuration =====
# According to the configuration in wiznet_init.py
BOARD = "w6300-evb-pico2"
BAUDRATE = 31250000
SCK_PIN = 17
CS_PIN = 16
IO0_PIN = 18
IO1_PIN = 19
IO2_PIN = 20
IO3_PIN = 21
RESET_PIN = 22
# ===== Network Configuration =====
# Static IP configuration (modify according to your network environment)
USE_DHCP = True
STATIC_IP = "192.168.1.50"
STATIC_SN = "255.255.255.0"
STATIC_GW = "192.168.1.1"
STATIC_DNS = "192.168.1.1" # Use Google DNS for improved reliability
def init_wiznet_spi():
"""Directly initialize the WIZnet SPI connection"""
print(f"初始化 {BOARD}...")
# Check whether WIZNET_PIO_SPI is available
try:
from machine import WIZNET_PIO_SPI
except ImportError:
print("错误: 当前固件不支持WIZNET_PIO_SPI")
raise
# Create the pin objects
sck = Pin(SCK_PIN)
cs = Pin(CS_PIN)
io0 = Pin(IO0_PIN)
io1 = Pin(IO1_PIN)
io2 = Pin(IO2_PIN)
io3 = Pin(IO3_PIN)
reset = Pin(RESET_PIN)
# Create the QSPI object (for the W6300)
print("创建WIZNET_PIO_SPI对象...")
spi = WIZNET_PIO_SPI(
baudrate=BAUDRATE,
sck=sck,
cs=cs,
io0=io0,
io1=io1,
io2=io2,
io3=io3
)
# Create the WIZNET6K network interface
print("创建WIZNET6K网络接口...")
nic = network.WIZNET6K(spi, cs, reset)
# Activate the network interface
try:
nic.active(True)
print("网络接口已激活")
except AttributeError:
print("注意: active()方法不支持,继续...")
return nic
def configure_network(nic):
"""Configure network parameters"""
if USE_DHCP:
print("使用DHCP自动获取IP...")
try:
nic.ifconfig("dhcp")
print(nic.ifconfig())
except Exception as e:
print(f"DHCP配置失败: {e}")
return False
else:
print(f"配置静态IP: {STATIC_IP}")
try:
nic.ifconfig((STATIC_IP, STATIC_SN, STATIC_GW, STATIC_DNS))
except Exception as e:
print(f"静态IP配置失败: {e}")
return False
# Wait for the network connection
print("等待网络连接...")
for i in range(10): # Wait up to 10 seconds
if nic.isconnected():
print("网络已连接!")
return True
print(f"等待中... ({i+1}/10)")
time.sleep(1)
print("网络连接超时")
return False
nic = init_wiznet_spi()
configure_network(nic)
# ================== Cookie test routes ==================
@app.route("/set_cookie", methods=["GET"])
def set_cookie(req):
"""Test endpoint for setting cookies"""
resp = Response("Cookie设置成功!")
# Set several test cookies
resp.set_cookie("user", "李四", max_age=3600, path="/")
resp.set_cookie("session_id", "abc123xyz", max_age=7200, path="/")
resp.set_cookie("theme", "dark", max_age=86400, path="/")
resp.set_cookie("preference", "zh-CN", path="/api")
return resp
@app.route("/get_cookie", methods=["GET"])
def get_cookie(req):
"""Get and display all cookies"""
cookies = req.cookies
cookie_list = []
for name, value in cookies.items():
cookie_list.append(f"{name}: {value}")
html = f"""
<html>
<head><title>Cookie Test</title></head>
<body>
<h1>Current Cookies ({len(cookie_list)})</h1>
<ul>
"""
for cookie in cookie_list:
html += f"<li>{cookie}</li>"
html += """
</ul>
<p>
<a href="/set_cookie">Set Cookie</a> |
<a href="/clear_cookie">Clear Cookie</a> |
<a href="/stream">Test Streaming Response</a>
</p>
</body>
</html>
"""
return Response(html, content_type="text/html")
@app.route("/clear_cookie", methods=["GET"])
def clear_cookie(req):
"""Clear all cookies (by setting an expiration time)"""
resp = Response("Cookie已清除!")
# Clear the cookie
resp.set_cookie("user", "", max_age=0, path="/")
resp.set_cookie("session_id", "", max_age=0, path="/")
resp.set_cookie("theme", "", max_age=0, path="/")
resp.set_cookie("preference", "", max_age=0, path="/api")
return resp
@app.route("/cookie_counter", methods=["GET"])
def cookie_counter(req):
"""Cookie counter example"""
count = int(req.cookies.get("visit_count", "0"))
count += 1
resp = Response(f"""
<html>
<body>
<h1>Welcome!</h1>
<p>This is your visit number {count} to this page.</p>
<p><a href="/">Back to home</a></p>
</body>
</html>
""")
resp.set_cookie("visit_count", str(count), max_age=31536000, path="/")
return resp
# ================== Streaming response test routes ==================
@app.route("/stream", methods=["GET"])
def stream_test(req):
"""Basic streaming response example"""
def generate():
# The first yield can be a header patch
yield {"Content-Type": "text/plain; charset=utf-8", "X-Streaming": "true"}
# Generate the streaming content
for i in range(5):
yield f"这是第 {i+1} 条流式数据\n"
time.sleep(0.5) # Simulate a delay
return Response(generate())
@app.route("/stream_json", methods=["GET"])
def stream_json(req):
"""Streaming JSON data"""
def generate():
# Set Content-Type to JSON
yield {"Content-Type": "application/json", "X-Streaming": "true"}
# Start the array
yield "[\n"
for i in range(5):
item = json.dumps({
"id": i + 1,
"timestamp": time.time(),
"message": f"数据块 {i+1}"
})
if i < 4:
yield f" {item},\n"
else:
yield f" {item}\n"
time.sleep(0.3)
# End the array
yield "]\n"
return Response(generate())
@app.route("/stream_sse", methods=["GET"])
def stream_sse(req):
"""Server-Sent Events (SSE) example"""
def generate():
# SSE requires a specific Content-Type
yield {
"Content-Type": "text/event-stream",
"Cache-Control": "no-cache",
"Connection": "keep-alive"
}
for i in range(10):
# SSE format: event: message\ndata: {...}\n\n
data = json.dumps({
"count": i + 1,
"time": time.time(),
"message": f"update {i+1}"
})
yield f"event: message\ndata: {data}\n\n"
time.sleep(1) # Push once per second
return Response(generate())
@app.route("/stream_large", methods=["GET"])
def stream_large_data(req):
"""Generate a streaming response of large data (simulating large data transfer)"""
def generate():
# Return the headers first
yield {"Content-Type": "text/plain; charset=utf-8"}
# Generate 1000 rows of data
for i in range(1000):
yield f"行 {i+1}: " + "x" * 100 + "\n"
if i % 100 == 0: # Refresh every 100 lines
time.sleep(0.1)
return Response(generate())
# ================== Mixed Test Routes ==================
@app.route("/chat_stream", methods=["GET"])
def chat_stream(req):
"""Simulate a chatbot streaming response (and set a Cookie at the same time)"""
def generate():
# Set SSE headers
yield {
"Content-Type": "text/event-stream",
"Cache-Control": "no-cache",
"Connection": "keep-alive"
}
# Generate the streaming chat response
messages = [
"你好!我是AI助手。",
"我可以在流式响应中逐步显示回答。",
"这样你可以看到实时的回复过程。",
"同时,我也设置了会话Cookie。",
"再见!期待下次为你服务。"
]
for i, msg in enumerate(messages):
data = json.dumps({
"index": i + 1,
"message": msg,
"timestamp": time.time(),
"complete": i == len(messages) - 1
})
yield f"data: {data}\n\n"
time.sleep(1.5)
resp = Response(generate())
# Set the session Cookie
resp.set_cookie("chat_session", f"sess_{int(time.time())}", max_age=3600, path="/")
return resp
@app.route("/progress", methods=["GET"])
def progress_stream(req):
"""Progress bar streaming update example"""
def generate():
yield {"Content-Type": "text/html; charset=utf-8"}
yield """
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Streaming Progress Example</title>
<style>
.progress-bar {
width: 300px;
height: 20px;
border: 1px solid #ccc;
margin: 20px 0;
}
.progress-fill {
height: 100%;
background: #4CAF50;
width: 0%;
transition: width 0.3s;
}
.status {
font-family: monospace;
}
</style>
</head>
<body>
<h1>Streaming Progress Updates</h1>
<div class="progress-bar">
<div class="progress-fill" id="progress"></div>
</div>
<div class="status" id="status">Getting ready to start...</div>
"""
# Stream the progress updates
for progress in range(0, 101, 10):
if progress == 0:
continue
yield f"""
<script>
document.getElementById('progress').style.width = '{progress}%';
document.getElementById('status').innerHTML = 'Current progress: {progress}%';
</script>
"""
time.sleep(0.5)
yield """
<script>
document.getElementById('status').innerHTML = '✅ Done!';
</script>
<p>Progress update complete! <a href="/">Back to home</a></p>
</body>
</html>
"""
return Response(generate())
# ================== Home Page and Test Pages ==================
@app.route("/", methods=["GET"])
def index(req):
"""Home page, shows all test links"""
html = """
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Streaming and Cookie Test Framework</title>
<style>
body { font-family: Arial, sans-serif; margin: 40px; }
h1 { color: #333; }
.test-section { margin: 30px 0; padding: 20px; border-left: 4px solid #4CAF50; background: #f9f9f9; }
.test-list { list-style: none; padding: 0; }
.test-list li { margin: 10px 0; }
.test-list a {
display: inline-block;
padding: 8px 15px;
background: #4CAF50;
color: white;
text-decoration: none;
border-radius: 4px;
margin-right: 10px;
}
.test-list a:hover { background: #45a049; }
.code {
background: #f4f4f4;
padding: 10px;
border-radius: 4px;
font-family: monospace;
margin: 10px 0;
}
</style>
</head>
<body>
<h1>🎯 Streaming and Cookie Test Framework</h1>
<p>This is a backend for testing the streaming response and Cookie features of your framework.</p>
<div class="test-section">
<h2>🍪 Cookie Tests</h2>
<ul class="test-list">
<li><a href="/set_cookie">Set test Cookie</a></li>
<li><a href="/get_cookie">View current Cookie</a></li>
<li><a href="/clear_cookie">Clear all Cookies</a></li>
<li><a href="/cookie_counter">Visit counter (uses Cookie)</a></li>
</ul>
</div>
<div class="test-section">
<h2>🌊 Streaming Response Tests</h2>
<ul class="test-list">
<li><a href="/stream">Basic streaming text</a></li>
<li><a href="/stream_json">Streaming JSON data</a></li>
<li><a href="/stream_sse">Server-Sent Events (SSE)</a></li>
<li><a href="/stream_large">Large file streaming</a></li>
<li><a href="/chat_stream">Simulated chat streaming response</a></li>
<li><a href="/progress">Streaming progress updates</a></li>
</ul>
</div>
<div class="test-section">
<h2>🛠️ Test Tools</h2>
<p>Test with curl:</p>
<div class="code">
# Test Cookie<br>
curl -c cookies.txt http://localhost:8080/set_cookie<br>
curl -b cookies.txt http://localhost:8080/get_cookie<br><br>
# Test streaming response<br>
curl -N http://localhost:8080/stream<br>
curl -N http://localhost:8080/stream_sse
</div>
</div>
<div class="test-section">
<h2>📊 Framework Feature Verification</h2>
<p>Your framework supports the following features:</p>
<ul>
<li>✅ Flask-like route decorators</li>
<li>✅ Cookie setting and reading</li>
<li>✅ Streaming responses (generators)</li>
<li>✅ Automatic response header management</li>
<li>✅ Multiple content types (HTML/JSON/SSE)</li>
</ul>
</div>
</body>
</html>
"""
return Response(html, content_type="text/html")
# ================== API Test Endpoints ==================
@app.route("/api/data", methods=["GET"])
def api_data(req):
"""API endpoint test"""
data = {
"status": "success",
"data": {
"framework": "Micropython Flask-like",
"features": ["streaming", "cookies", "routing"],
"timestamp": time.time(),
"cookies_received": dict(req.cookies)
}
}
return Response(data, content_type="application/json")
@app.route("/api/stream_data", methods=["GET"])
def api_stream_data(req):
"""Streaming API endpoint"""
def generate():
yield {"Content-Type": "application/json"}
yield "{\n \"data\": [\n"
for i in range(5):
item = {
"id": i + 1,
"value": f"item_{i+1}",
"time": time.time()
}
if i < 4:
yield f" {json.dumps(item)},\n"
else:
yield f" {json.dumps(item)}\n"
time.sleep(0.5)
yield " ]\n}\n"
return Response(generate())
# ================== Error Handling Tests ==================
@app.route("/slow_stream", methods=["GET"])
def slow_stream(req):
"""Slow stream test, tests client disconnect handling"""
def generate():
try:
for i in range(10):
yield f"数据块 {i+1},时间: {time.time()}\n"
time.sleep(2) # Send once every 2 seconds
except Exception as e:
print(f"流中断: {e}")
return Response(generate())
@app.route("/error_stream", methods=["GET"])
def error_stream(req):
"""Simulate an error occurring in the stream"""
def generate():
for i in range(5):
if i == 2:
raise Exception("模拟流错误")
yield f"数据 {i+1}\n"
time.sleep(0.5)
return Response(generate())
# ================== Start the Server ==================
if __name__ == "__main__":
print("🎯 启动流式与Cookie测试服务器...")
print("🔗 访问地址: IP:80")
print("📁 Cookie测试: /set_cookie, /get_cookie, /clear_cookie")
print("🌊 流式测试: /stream, /stream_sse, /chat_stream")
print("🚀 按Ctrl+C停止服务器\n")
# Start the server
app.run(host="::", port=80)This document uses a hard-coded approach, yet the library supports both render_template () and render_template_string ().


