我不确定这是否是特定的Flask,但当我在dev模式下运行应用程序(http://localhost:5000)时,我无法从网络上的其他机器访问它(使用http://[dev-host-ip]:5000)。例如,当Rails处于开发模式时,它工作得很好。我找不到任何关于Flask开发服务器配置的文档。你知道应该配置什么来实现这个功能吗?


当前回答

这最终对我有用。

import os

然后把它放在你的python app.py或主文件的末尾。

if __name__ == "__main__":
    port = int(os.environ.get("PORT", 5000))
    app.run(host='0.0.0.0', port=port)

其他回答

在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应用程序

在项目根目录中创建文件.flaskenv。

这个文件中的参数通常是:

FLASK_APP=app.py
FLASK_ENV=development
FLASK_RUN_HOST=[dev-host-ip]
FLASK_RUN_PORT=5000

如果您有一个虚拟环境,请激活它并执行pip install python-dotenv。

这个包将使用.flaskenv文件,其中的声明将自动跨终端会话导入。

然后你就可以进行长距离跑步了

如果您使用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/

如果你的酷应用程序从外部文件加载了它的配置,就像下面的例子,那么不要忘记用HOST="0.0.0.0"更新相应的配置文件

cool.app.run(
    host=cool.app.config.get("HOST", "localhost"),
    port=cool.app.config.get("PORT", 9000)
)            

检查服务器上的特定端口是否打开以服务客户端?

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