
本文详细解释 Flask 应用中因函数定义缺失、返回语句遗漏和方法误用导致的 Invalid Syntax 错误,并提供可直接运行的修正代码与 HTML 模板优化建议。
本文详细解释 flask 应用中因函数定义缺失、返回语句遗漏和方法误用导致的 `invalid syntax` 错误,并提供可直接运行的修正代码与 html 模板优化建议。
在使用 Flask 构建 Web 应用时,初学者常因忽略 Python 的基本语法规则(如函数定义、缩进、返回值)而遇到 SyntaxError: invalid syntax。你提供的代码中存在三个关键问题,下面逐一说明并给出专业、可落地的修复方案。
? 核心问题解析与修复
-
@app.route("/") 后缺少视图函数定义
装饰器 @app.route("/") 必须紧接一个 def 函数声明,不能直接调用 render_template()。原代码:@app.route("/") # Render the index.html template reder_template("index.html") # ❌ 错误:无函数体,且拼写错误(应为 render_template)✅ 正确写法需明确定义函数,并用 return 返回模板:
@app.route("/") def homepage(): return render_template("index.html") -
app.return() 是非法方法
Flask 应用启动应使用 app.run(),而非 app.return()(Python 中不存在该方法)。
✅ 修正为:if __name__ == "__main__": app.run(host="0.0.0.0", port=5000, debug=True) # 推荐添加参数便于树莓派访问 -
HTML 模板存在结构与语义错误
原 HTML 中:是无效标签(应为 );
不是合法 HTML 标签,按钮内容应放在 - 缺少 声明,可能引发浏览器兼容性问题。
✅ 推荐修正后的 templates/index.html:
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <title>Wake on LAN Website!</title> <style> body { font-family: sans-serif; text-align: center; margin-top: 2rem; } button { padding: 0.75rem 1.5rem; font-size: 1.1rem; background: #4CAF50; color: white; border: none; border-radius: 4px; cursor: pointer; } button:hover { background: #45a049; } </style> </head> <body> <h1>Wake on LAN Website</h1> <p>This website allows you to turn on your PC remotely using Wake-on-LAN.</p> <button onclick="window.location.href='/wakeup'">Turn on PC</button> </body> </html>
✅ 完整可运行的 app.py(已整合修复)
from flask import Flask, render_template
from wakeonlan import send_magic_packet
app = Flask(__name__)
PC_MAC = "AA:BB:CC:DD:EE:FF" # ✅ 替换为你的实际 MAC 地址(格式必须为 XX:XX:XX:XX:XX:XX)
@app.route("/")
def homepage():
return render_template("index.html")
@app.route("/wakeup")
def wakeup():
try:
send_magic_packet(PC_MAC)
return "✅ Your PC has been woken up successfully!"
except Exception as e:
return f"❌ Failed to send magic packet: {str(e)}"
if __name__ == "__main__":
# 在树莓派上建议监听所有接口,方便局域网访问
app.run(host="0.0.0.0", port=5000, debug=True)⚠️ 注意事项与最佳实践
- 目录结构必须严格匹配:Flask 默认从 templates/ 目录加载 HTML 文件,请确保 index.html 位于 ./templates/index.html(与 app.py 同级目录下有 templates 文件夹)。
- MAC 地址格式:wakeonlan 要求 MAC 地址为 XX:XX:XX:XX:XX:XX 或 XX-XX-XX-XX-XX-XX 格式,大小写不敏感,但不可省略分隔符。
-
权限与网络配置:在树莓派上运行前,请确认:
- 已安装 wakeonlan:pip install wakeonlan
- 目标 PC 已启用 BIOS 中的 Wake-on-LAN 并连接有线网络(WoL 通常不支持 Wi-Fi);
- 树莓派与 PC 处于同一局域网。
- 生产环境提醒:debug=True 和 host="0.0.0.0" 仅适用于开发测试;部署到公网前务必禁用 debug 模式,并使用 Nginx + Gunicorn 等生产级服务器。
通过以上修正,你的 Flask WoL 网站即可在树莓派上稳定运行——点击按钮即可远程唤醒主机。理解“装饰器绑定函数”和“视图必须返回响应”这两条核心原则,将帮你避开 90% 的入门级 Flask 报错。

















