Raspberry Pi控制LED灯带时出现AttributeError:'MyServer'无'strip1'属性
解决Raspberry Pi HTTP控制LED灯带的AttributeError问题
我尝试用Raspberry Pi 4通过HTTP接口控制LED灯带,编写了Strip类处理灯带显示效果,希望用户点击HTTP界面按钮时调用类方法点亮灯带,但点击"On"按钮时触发如下错误:
Error @ line 44: self.strip1.fill_red() AttributeError: 'MyServer' object has no attribute 'strip1'
HTTP网站可正常访问,但POST请求处理时找不到strip1属性。
问题原因
BaseHTTPRequestHandler的初始化流程特殊:当HTTPServer处理请求时,会调用handler的构造函数,而super().__init__(*args, **kwargs)内部会提前执行请求解析逻辑,此时你在__init__中设置的self.strip1还未完成绑定,导致后续请求处理时无法找到该属性。
解决方案
通过类属性共享strip1实例,避免在__init__中传递参数导致的初始化时序问题。修改代码如下:
修改后的服务器类(MyServer)
from typing import Tuple from View.strip import Strip from http.server import BaseHTTPRequestHandler, HTTPServer class MyServer(BaseHTTPRequestHandler): # 定义类属性存储strip实例 strip1 = None def __init__(self, *args, **kwargs) -> None: super().__init__(*args, **kwargs) def do_HEAD(self): self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() def _redirect(self, path): self.send_response(303) self.send_header('Content-type', 'text/html') self.send_header('Location', path) self.end_headers() def do_GET(self): html = ''' <html> <body style="width:960px; margin: 20px auto;"> <h1>Welcome to Rahul's Raspberry Pi LED Strip Controller</h1> <form action="/" method="POST"> Strip Options: <input type="submit" name="submit" value="On"> <input type="submit" name="submit" value="Off"> </form> </body> </html> ''' self.do_HEAD() self.wfile.write(html.encode("utf-8")) def do_POST(self): content_length = int(self.headers['Content-Length']) post_data = self.rfile.read(content_length).decode("utf-8") post_data = post_data.split("=")[1] if post_data == 'On': MyServer.strip1.fill_red() print('On') else: print('Off') MyServer.strip1.clear_strip() print("LED is {}".format(post_data)) self._redirect('/') # Redirect back to the root url
修改后的主文件
from View.server import MyServer from http.server import HTTPServer from View.strip import Strip import board strip1 = Strip(board.D18,55,0.05) # 将strip实例绑定到MyServer的类属性 MyServer.strip1 = strip1 server_address = ('IPaddresshere', 8000) httpd = HTTPServer(server_address, MyServer) print('Server running at http://IPaddresshere/') httpd.serve_forever()
额外提示
Strip类的fill_red方法中,当前填充的颜色是(0,220,0)(绿色),如果需要红色,应该改为(220,0,0)。
内容的提问来源于stack exchange,提问作者Rahul Singh
相关产品推荐
相关产品推荐

