我不确定这是否是特定的Flask,但当我在dev模式下运行应用程序(http://localhost:5000)时,我无法从网络上的其他机器访问它(使用http://[dev-host-ip]:5000)。例如,当Rails处于开发模式时,它工作得很好。我找不到任何关于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/

以防你需要从外部网络测试你的应用程序。 只要用ngrok.com把它提供给整个互联网 它会像开发服务器一样部署它,但很快就会在本地部署,为我节省了很多时间,不,我和那家公司没有关系:)

只需要确保在你的flask应用程序中更改端口: app.run(主机= 0.0.0.0,端口= 80)

如果以上解决方案都不起作用,请尝试手动在url的开头添加“http://”。

Chrome可以从搜索查询中区分“[ip-address]:5000”。但有时候,这种方式会起作用一段时间,然后就停止了联系,似乎我什么都没改变。我的假设是浏览器有时可能会自动在https://前加上前缀(它不应该这样,但这在我的例子中解决了这个问题)。

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

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

Eg: