Skip to main content
 首页 » 编程设计

python之Flask 应用程序未连接到端口

2025年05月04日8mq0036

我正在学习 Miguel Grinberg 的 Flask Web 开发教程,并且复制了这段代码

from flask import Flask 
app = Flask(__name__) 
@app.route('/') 
def index(): 
    return '<h1>Hello World!</h1>' 
if __name__ == '__main__': 
    app.run(debug=True) 

在 Jupyter 上我得到了这个结果: * 在 http://127.0.0.1:5000/ 上运行(按 CTRL+C 退出) *重新启动统计 发生异常,使用 %tb 查看完整的回溯。 系统导出:1

如果我打开 http://127.0.0.1:5000/该页面只是永远加载,如果我在 Powershell 上运行代码也是一样(但没有给出错误)。 我试图寻找类似的问题,但我找不到任何东西,你能告诉我我做错了什么以及我能做些什么来解决这个问题吗?提前致谢。

编辑: 正如 Mariusz 所问,这是我通过在单元格开头添加 %tb 得到的错误:

SystemExit                                Traceback (most recent call last) 
<ipython-input-4-5757c6364c65> in <module>() 
      8     return '<h1>Hello World!</h1>' 
      9 if __name__ == '__main__': 
---> 10     app.run(debug=True) 
 
C:\Users\Antonio\Anaconda3\lib\site-packages\flask\app.py in run(self, host, port, debug, **options) 
    841         options.setdefault('passthrough_errors', True) 
    842         try: 
--> 843             run_simple(host, port, self, **options) 
    844         finally: 
    845             # reset the first request information if the development server 
 
C:\Users\Antonio\Anaconda3\lib\site-packages\werkzeug\serving.py in run_simple(hostname, port, application, use_reloader, use_debugger, use_evalex, extra_files, reloader_interval, reloader_type, threaded, processes,     request_handler, static_files, passthrough_errors, ssl_context) 
    690         from ._reloader import run_with_reloader 
    691         run_with_reloader(inner, extra_files, reloader_interval, 
--> 692                           reloader_type) 
    693     else: 
    694         inner() 
 
C:\Users\Antonio\Anaconda3\lib\site-packages\werkzeug\_reloader.py in run_with_reloader(main_func, extra_files, interval, reloader_type) 
    248             reloader.run() 
    249         else: 
--> 250             sys.exit(reloader.restart_with_reloader()) 
    251     except KeyboardInterrupt: 
    252         pass 
 
SystemExit: 1 

请您参考如下方法:

你能试试这个代码,看看它是否有效

app.run(debug=True, use_reloader=False)