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


当前回答

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

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

其他回答

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

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

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

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

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

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

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

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

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

我也有同样的问题,我使用PyCharm作为编辑器,当我创建项目时,PyCharm创建了一个Flask服务器。我所做的就是用Python创建一个服务器,方法如下:

基本上我所做的就是创建一个新的服务器,如果不是python的话,就是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)