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

使用Flask时localhost:5000无法访问,请求排查故障原因

问题分析与解决办法

嘿,我一眼就揪出问题所在了,咱们一步步理清楚:

核心问题:启动条件判断错误

你的代码里这行判断写岔了:

if __name__=="__name__":

在Python里,当你直接运行脚本时,__name__变量的实际值是'__main__',而不是字符串"__name__"。这就导致app.run(debug=True)完全没被执行——服务器根本没启动,自然访问不了页面。

修正后的代码

把判断条件改成Python的标准写法就行:

from flask import Flask
app = Flask(__name__)

@app.route('/')
def index():
    return 'This is the home page'

if __name__ == '__main__':
    app.run(debug=True)

验证效果

修改后重新在终端执行:

python helloworld.py

这时候你应该能看到终端输出类似这样的内容:

  • Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
  • Restarting with stat
  • Debugger is active!
  • Debugger PIN: XXX-XXX-XXX

这说明Flask服务器已经正常启动了,此时再访问http://localhost:5000就能看到你的首页内容啦。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 07:08:14