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


当前回答

对我来说,我遵循上面的答案,并稍加修改:

只需在命令提示符上使用ipconfig获取ipv4地址 转到flask代码所在的文件 在主函数中写入app.run(host= '你的ipv4地址')

Eg:

其他回答

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

基本上我所做的就是创建一个新的服务器,如果不是python的话,就是flask

我希望这对你有所帮助

您还可以通过环境变量设置主机(将其暴露在面向IP地址的网络上)和端口。

$ export FLASK_APP=app.py
$ export FLASK_ENV=development
$ export FLASK_RUN_PORT=8000
$ export FLASK_RUN_HOST=0.0.0.0

$ flask run
 * Serving Flask app "app.py" (lazy loading)
 * Environment: development
 * Debug mode: on
 * Running on https://0.0.0.0:8000/ (Press CTRL+C to quit)
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 329-665-000

参见如何获取所有可用的命令选项来设置环境变量?

添加主机='0.0.0.0'到app.run '。

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)

如果你得到OSError: [WinError 10013]试图访问一个套接字在Windows上的访问权限禁止的方式,你要么没有权限使用端口,或者其他东西正在使用它,你可以通过netstat -na|findstr 5000找到。

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

如果你在访问使用PyCharm部署的Flask服务器时遇到问题,请考虑以下因素:

PyCharm不会直接运行你的主.py文件,因此if __name__ == '__main__':中的任何代码都不会被执行,并且任何更改(如app.run(host='0.0.0.0', port=5000))都不会生效。

相反,您应该使用Run Configurations配置Flask服务器,特别是将——host 0.0.0.0——port 5000放置到附加选项字段中。

更多关于配置Flask服务器在PyCharm