访问局域网内Python Web服务器时出现“Bad Gateway”错误求助
Flask服务器局域网访问出现"Bad Gateway"错误的排查与修复
代码中的致命错误
你的代码存在直接导致服务器内部崩溃的问题:
- 开头导入的
from asyncio import tasks是asyncio的模块,并非用于存储Todo任务的列表。在TodoResource的post方法中调用tasks.append(task)会触发AttributeError: module 'asyncio.tasks' has no attribute 'append',导致服务器处理请求时直接报错,这很可能是"Bad Gateway"的核心原因。
修复方式:
替换该导入语句,自定义一个空列表用于存储任务:
# 移除 from asyncio import tasks,替换为: tasks = [] import json import os from flask import Flask, render_template, jsonify, url_for, request from flask_restful import Api, Resource, reqparse
网络与配置排查
除了代码错误,以下配置问题也可能导致"Bad Gateway":
- 确认服务器IP正确性:你访问的
xx.xx.xx.xx必须是服务器在局域网内的实际IP地址(可通过ipconfig/ip addr查看),不能使用公网IP(局域网内访问场景)。 - 开放5000端口防火墙:服务器的防火墙需要允许5000端口的入站连接。Windows可在防火墙高级设置中添加端口规则;Linux执行
ufw allow 5000或firewall-cmd --add-port=5000/tcp。 - 检查端口占用:确保5000端口未被其他程序占用。Windows用
netstat -ano | findstr :5000,Linux/macOS用lsof -i :5000查看,若被占用需更换端口或关闭占用程序。 - 确认局域网连通性:客户端设备需与服务器处于同一局域网,可通过ping服务器IP验证连通性。
代码优化建议(避免后续问题)
你的home路由中手动修改JSON文件的逻辑容易生成无效JSON格式,建议改用更可靠的方式:
@app.route('/', methods=["GET", "POST"]) def home(): if request.method == 'POST': data = request.form.to_dict() file_path = "./data.json" try: # 读取现有数据或初始化空列表 if os.path.isfile(file_path) and os.stat(file_path).st_size > 0: with open(file_path, "r") as f: existing_data = json.load(f) else: existing_data = [] # 添加新数据并重新写入 existing_data.append(data) with open(file_path, "w") as f: json.dump(existing_data, f, indent=2) except Exception as e: print(f"数据写入错误: {e}") return render_template('home.html')
验证步骤
- 修复代码后重启服务器,确认控制台无启动报错,显示
* Running on all addresses (0.0.0.0)。 - 在服务器本地访问
localhost:5000,验证页面加载、POST请求功能正常。 - 在局域网其他设备上使用服务器本地IP+端口访问,如
192.168.1.100:5000。
内容的提问来源于stack exchange,提问作者DYLAN VURBIER
相关产品推荐
相关产品推荐

