我不确定这是否是特定的Flask,但当我在dev模式下运行应用程序(http://localhost:5000)时,我无法从网络上的其他机器访问它(使用http://[dev-host-ip]:5000)。例如,当Rails处于开发模式时,它工作得很好。我找不到任何关于Flask开发服务器配置的文档。你知道应该配置什么来实现这个功能吗?
当前回答
虽然这是可能的,但您不应该在生产中使用Flask开发服务器。Flask开发服务器的设计并不是特别安全、稳定或高效。有关正确的解决方案,请参阅部署文档。
flask run的——host选项或app.run()的host参数控制开发服务器侦听的地址。默认情况下,它运行在localhost上,将其更改为flask run——host=0.0.0.0(或app.run(host="0.0.0.0"))以运行在您机器的所有IP地址上。
0.0.0.0是一个不能直接在浏览器中使用的特殊值,您需要在网络中导航到机器的实际IP地址。您可能还需要调整防火墙以允许外部访问该端口。
Flask快速入门文档在“外部可见服务器”部分解释了这一点:
If you run the server you will notice that the server is only accessible from your own computer, not from any other in the network. This is the default because in debugging mode a user of the application can execute arbitrary Python code on your computer. If you have the debugger disabled or trust the users on your network, you can make the server publicly available simply by adding --host=0.0.0.0 to the command line: $ flask run --host=0.0.0.0 This tells your operating system to listen on all public IPs.
其他回答
检查服务器上的特定端口是否打开以服务客户端?
Ubuntu或Linux发行版
sudo ufw enable
sudo ufw allow 5000/tcp //allow the server to handle the request on port 5000
配置应用程序以处理远程请求
app.run(host='0.0.0.0' , port=5000)
python3 app.py & #run application in background
如果以上解决方案都不起作用,请尝试手动在url的开头添加“http://”。
Chrome可以从搜索查询中区分“[ip-address]:5000”。但有时候,这种方式会起作用一段时间,然后就停止了联系,似乎我什么都没改变。我的假设是浏览器有时可能会自动在https://前加上前缀(它不应该这样,但这在我的例子中解决了这个问题)。
如果您使用flask可执行文件启动服务器,请使用flask run——host=0.0.0.0将默认值从127.0.0.1更改为开放给非本地连接。
If you run the server you will notice that the server is only accessible from your own computer, not from any other in the network. This is the default because in debugging mode a user of the application can execute arbitrary Python code on your computer. If you have the debugger disabled or trust the users on your network, you can make the server publicly available simply by adding --host=0.0.0.0 to the command line: $ flask run --host=0.0.0.0 This tells your operating system to listen on all public IPs.
参考:https://flask.palletsprojects.com/quickstart/
在CMD(命令提示符)上进入您的项目路径,并执行以下命令:-
设置FLASK_APP = ABC.py
设置FLASK_ENV =发展
flask运行-h [yourIP] -p 8080
你会在CMD上得到以下o/p:-
服务Flask应用程序" experimental .py"(延迟加载) 开发环境: 调试模式:开启 使用stat重新启动 调试器已激活! 调试器PIN: 199-519-700 运行http://[yourIP]:8080/(按CTRL+C退出)
现在您可以在另一台机器上使用http://[yourIP]:8080/ url访问您的flask应用程序
如果你的酷应用程序从外部文件加载了它的配置,就像下面的例子,那么不要忘记用HOST="0.0.0.0"更新相应的配置文件
cool.app.run(
host=cool.app.config.get("HOST", "localhost"),
port=cool.app.config.get("PORT", 9000)
)